问题描述:

My project is basically like a Reddit feed that updates in real-time. I'm trying to use AJAX to poll the server at intervals for updates on 15 items at a time.

I wrote a for loop but it caused the browser to lock up (I'm guessing too many XHRs?).

How can I poll each item on the Reddit-esque feed without locking up the browser? What is the most efficient way to do this?

Should I use long-polling if there are 100+ clients using the web app at the same time? Or should I opt for smart polling (increasing the wait time between requests if no data)?

Thanks! I'm still new to AJAX!

for (var i=0; i < id_array_len; i++) {

// Grab current reply count

var reply = $("#repl"+item_id).html();

var url= *php function here*

var ajaxRequest;

try{

// Opera 8.0+, Firefox, Safari

ajaxRequest = new XMLHttpRequest();

} catch (e){

// Internet Explorer Browsers

try{

ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

try{

ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e){

// Something went wrong

alert("Your browser does not support AJAX!");

return false;

}

}

}

ajaxRequest.onreadystatechange = function(){

if (ajaxRequest.readystate == 4){

live_feed_data_tot = ajaxRequest.responseText;

if (live_feed_data_tot.trim() == "no change" || live_feed_data_tot.trim() == "no meme" || live_feed_data_tot.trim() == "no response"){

console.log("(no update)");

} else {

var live_feed_data = live_feed_data_tot.split(',');

if (live_feed_data[1] == 'reply') {

// Reply count has changed

new_reply = live_feed_data[0].trim();

// Update actual number

$("#repl"+item_id).html(new_reply);

}

}

}

}

ajaxRequest.open('POST', url, true);

ajaxRequest.send();

网友答案:

Use longpolling with a long (appropriate for your app of course) timeout. Your call needs to be asynchronous of course. As long as there is no data to deliver, the server holds the answer back, until the timeout is about to be reached. As soon as the client gets an answer, trigger the next longpoll in your complete()-Block. This way you can minimize the number of requests.

EDIT: after seeing your code i see you use native ajax but use jQuery for selecting. I suggest you to use jQuery for your ajax requests as well (jQuery .ajax() Doku).

Your code should look something like this:

function doAjaxLongpollingCall(){

   $.ajax({
     url: "...",
     timeout: <prettylong>,
     success: function(){
       //process your data
     },
     complete: function(){
       doAjaxLongpollingCall();
     }
   });
}
网友答案:

If you are doing a lot of users, switch to socket.io and save yourself the hassle. It uses websockets (which use a push mechanism) and does fallbacks to other mechanisms like flash sockets or long polling if thats not available in the browser. Requires you to create this piece of your app in node.js though.

相关阅读:
Top