1

这是我的 ajax 代码,所以请谁能告诉我如何将此代码更改为长轮询?

这是我的代码:-

var chat = {}
chat.fetchMessages = function () {
  $.ajax({
    url: 'ajax/ajax/chat.php',
    type: 'POST',
    data: { method: 'fetch' },
    success: function(data) {
      $('#chats').html(data);
    }
  }); 
}
chat.interval = setInterval(chat.fetchMessages, 1000);
4

2 回答 2

2

您必须将 fetchMessage 的下一个调用放在前一个的回调中:

var chat = {}
chat.fetchMessages = function () {
  $.ajax({
    url: 'ajax/ajax/chat.php',
    type: 'POST',
    data: { method: 'fetch' },
    success: function(data) {
      $('#chats').html(data);
      chat.fetchMessages(); // let's do it again
    }
  }); 
}
chat.fetchMessages(); // first call
于 2013-04-05T17:51:31.710 回答
0

The above code seems to work fine but this will call function immediately as a result of this it would increase the traffic and possibly for continuous long polling memory usage by the browser will increase . Try to use settimeout to keep some duration between calls made , would be good if you clear cache too . Other option would be comet or signaR .

于 2013-04-06T12:20:24.863 回答