having multiple ajax responses for one request

拜拜、爱过 提交于 2020-01-23 19:03:09

问题


I have some problems with ajax responses. Everything is working okay, however I got some strange behaviours. I am making an ajax-based chat. So, I use ajax requests-responses to make the stuff work. It is working fine, albeit since I started to use 2 polling functions sometimes the responses are retrieved multiple times. In specifics: I send 1 ajax package for message polling, and 1 ajax package for userlist polling. Both of them are sent periodically! Furthermore, they are sent with same frequency in about same time. Sometimes they have a problem: for a request multiple responses are sent back. All packages have a timestamp and they are logged on the server-side. On the server the package only got in once (I am sure based on logging, and using multiple browsers at the same time). The browser makes the response about 3-4 times. All messages are completely same, with the same timestamp. This usually happens when there is a heavy load on the browser. I tried to disable cache in the header but it does not help too. Please help with any information or idea about the problem.


回答1:


Why use two requests? Combine them into a single "anything new for me?" type, and send back both responses at the same time. You can embed arbitrary data structures into an JSON response, so it'll be easy to do something like:

$data = array(
   'user_query' => array(
        'status' => false   // nothing new
   ),
   'mesage_query' => array(
        'status' => true // got some new messages
        'messages' => array (
            0 => array(... new message #1 data ...),
            1 => array(... new message #2 data ...)
            etc...
        )
   )
);
echo json_encode($data)

and then in your client-side script, in the ajax response handler (assuming jquery):

$.ajax(blah blah blah
    ....
    success: function(data) {
         if (data['messages'].status) {
              show_new_messages(data['messages']);
         }
         if (data['user_query'].status) {
              show_new_users(data['user_query']);
         }
    }
});


来源:https://stackoverflow.com/questions/8379957/having-multiple-ajax-responses-for-one-request

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!