AJAX轮询和循环

AJAX polling and looping

本文关键字:循环 AJAX      更新时间:2023-09-26

我的项目基本上就像一个实时更新的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()-块中触发下一个长轮询。这样可以最大限度地减少请求数量。

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

你的代码应该是这样的:

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

如果你有很多用户,请切换到socket.io,省去麻烦。它使用websocket(使用推送机制),如果浏览器中没有flash socket或长轮询,则会回退到其他机制。不过,需要您在node.js中创建应用程序的这一部分。