问题
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