How to change this ajax code to long polling [duplicate]

血红的双手。 提交于 2019-12-31 03:21:11

问题


This is my ajax code so please can anyone tell me how can i change this code to long polling ?

Here is my code :-

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);

回答1:


You have to put the next call of fetchMessage in the callback of the previous one :

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



回答2:


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 .



来源:https://stackoverflow.com/questions/15838715/how-to-change-from-ajax-polling-to-long-polling

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