gpt4 book ai didi

javascript - AJAX 轮询和循环

转载 作者:行者123 更新时间:2023-11-29 22:25:23 25 4
gpt4 key购买 nike

我的项目基本上就像一个实时更新的 Reddit 提要。我正在尝试使用 AJAX 每隔一段时间轮询一次服务器以获取 15 个项目的更新。

我写了一个 for 循环,但它导致浏览器锁定(我猜 XHR 太多了?)。

如何在不锁定浏览器的情况下轮询 Reddit 式提要上的每个项目?最有效的方法是什么?

如果有 100 多个客户端同时使用 Web 应用程序,我应该使用长轮询吗?或者我应该选择智能轮询(如果没有数据则增加请求之间的等待时间)?

谢谢!我还是 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();

最佳答案

使用长超时(当然适合您的应用程序)的长轮询。您的调用当然需要异步。只要没有数据要传送,服务器就会保留答案,直到即将达到超时为止。一旦客户端得到答案,就在您的 complete()-Block 中触发下一个 longpoll。通过这种方式,您可以最大限度地减少请求数量。

编辑:在看到您的代码后,我看到您使用 native ajax 但使用 jQuery 进行选择。我建议您也对 ajax 请求使用 jQuery ( jQuery .ajax() Doku )。

您的代码应如下所示:

function doAjaxLongpollingCall(){

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

关于javascript - AJAX 轮询和循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9811255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com