有一个要求多个Ajax响应多个、有一个、Ajax

2023-09-10 18:17:19 作者:很酷不放纵

我有一些问题Ajax响应。一切工作正常,但我得到了一些奇怪的行为。 我想提出一个基于AJAX的聊天。所以,我用AJAX请求 - 响应,使东西的工作。它做工精细,虽然自从我开始使用有时响应检索多次2轮询功能。 在具体:我送1 AJAX包的消息轮询和1阿贾克斯包用户列表查询。他们两人都是定期发送!此外,它们在大约同一时间一起发送相同的频率。 有时,他们有一个问题:一个请求多响应发送回去。所有的包有时间戳记,并在登录服务器端。在服务器软件包只得到了在一次(我肯定基于日志记录,并使用多个浏览器在同一时间)。浏览器做出反应约3-4倍。所有消息都完全一样,具有相同的时间戳。这通常发生时,有在浏览器上的重负载。 我试图禁用缓存的头,但它并不能帮助了。 请帮助任何有关问题的信息和想法。

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.

推荐答案

为什么要用两个请求?它们合并成一个单一的任何新的东西给我吗?型,并发送回两种反应同时。您可以嵌入任意数据结构到一个JSON响应,因此这将是容易做到的是这样的:

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)

,然后在客户端脚本,在Ajax响应处理程序(假设jQuery的):

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']);
         }
    }
});
 
精彩推荐
图片推荐