【发布时间】:2012-04-06 08:43:28
【问题描述】:
我的项目基本上就像一个实时更新的 Reddit 提要。我正在尝试使用 AJAX 定期轮询服务器以一次更新 15 个项目。
我写了一个 for 循环,但它导致浏览器锁定(我猜 XHR 太多了?)。
如何在不锁定浏览器的情况下轮询 Reddit 式提要中的每个项目?最有效的方法是什么?
如果有 100 多个客户端同时使用网络应用,我应该使用长轮询吗?或者我应该选择智能轮询(如果没有数据,则增加请求之间的等待时间)?
谢谢!我还是 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();
【问题讨论】:
-
向我们展示循环。我已经在没有锁定浏览器的情况下完成了几次不同的操作,所以我希望它在你的代码中。
-
添加了代码 -- 非常感谢帮助!
标签: javascript ajax polling