簡體   English   中英

隊列AJAX調用

[英]Queue AJAX calls

您好我正在做一個橫向滾動網站,如: http//vanityclaire.com/

然而,在主頁加載之后,我使用jQuery .load()在家里的孩子們中,而不是擁有一個大的HTML文件。

目前我為每個div和ajax in the url位於標題中。 但是AJAX返回亂序,並且當我添加更多頁面時,不要想用30多個http://請求對服務器進行操作。

我如何同步執行AJAX調用,即在請求之前等待第一個回復,或者甚至一次發送兩個。

我一直在淘,也無法弄清楚我需要什么。

這是我的HTML:

<div id="mainLayout" class="fullwidth scrollArea">
    <div class="scrollItems">
      <div id="page-1" class="scrollItem" title="/">
        <div>HOME PAGE CONTENT</div>
      </div>
      <div id="page-2" class="scrollItem" title="/Page2.html">
        <div class="loading"> </div>
      </div>
      <div id="page-3" class="scrollItem" title="/Page3.html">
        <div class="loading"> </div>
      </div>

      <div id="page-4" class="scrollItem" title="/Page4.html">
        <div class="loading"> </div>
      </div>
      <div id="page-5" class="scrollItem" title="/Page5.html">
        <div class="loading"> </div>
      </div>
    </div>
  </div>

我的JS:

function s_loadingInitialPages() {
    var loadingItems = new Array();
    $(".scrollArea .scrollItem").each(function () {
        if ($(this).attr('title') != '/') {
            var oDelem = $(this);
            loadingItems.push(oDelem);
            //alert('test');
        }
    });

    for (i = 0; i < loadingItems.length; i++) {
        // title attribute is the URL to get
        var ajaxURL = loadingItems[i].attr("title") + '?ajaxPageContent=';
        $(loadingItems[i]).load(ajaxURL);

    }
}

是否有插件我可以繼續向隊列添加功能,讓它處理它?

訣竅是使用回調。 你進行一次ajax調用,並在成功回調時創建下一個調用。

要做到這一點,只需將它們全部添加到隊列中並在其周圍放置一個包裝器,逐個發送它們。

我幾天前寫了一篇。 我將在一秒鍾內向您展示一個實現。

// Buffer class. Has a public append method that expects some kind of Task.
// Constructor expects a handler which is a method that takes a ajax task
// and a callback. Buffer expects the handler to deal with the ajax and run
// the callback when it's finished
function Buffer(handler) {
    var queue = [];

    function run() {
        var callback = function () {
             // when the handler says it's finished (i.e. runs the callback)
             // We check for more tasks in the queue and if there are any we run again
             if (queue.length > 0) {
                  run();
             }
        }
        // give the first item in the queue & the callback to the handler
        handler(queue.shift(), callback);
    } 

    // push the task to the queue. If the queue was empty before the task was pushed
    // we run the task.
    this.append = function(task) {
        queue.push(task);
        if (queue.length === 1) {
            run();
        }
    }

}

// small Task containing item & url & optional callback
function Task(item, url, callback) {
    this.item = item;
    this.url = url;
    this.callback = callback
}

// small handler that loads the task.url into the task.item and calls the callback 
// when its finished
function taskHandler(task, callback) {
    $(task.item).load(task.url, function() {
        // call an option callback from the task
        if (task.callback) task.callback();
        // call the buffer callback.
        callback();
    });
}

// create a buffer object with a taskhandler
var buffer = new Buffer(taskHandler);

for (i = 0; i < loadingItems.length; i++) {
    // title attribute is the URL to get
    var ajaxURL = loadingItems[i].attr("title") + '?ajaxPageContent=';
    buffer.append(new Task(loadingItems[i], ajaxURL));
}

為代碼牆道歉。 只需實現自己的任務和處理程序。 只要處理程序在完成處理任務時調用第二個參數(回調),緩沖區就會起作用。

然后只需傳遞一個任務和一個處理程序。 處理程序執行ajax並在ajax返回時從緩沖區調用回調。

對於您的具體示例,如果您的加載需要很長時間,那么這將花費很長時間來加載所有30. ajax的目的是讓服務器並行執行。

在您的情況下,一個更好的解決方案是發出30個請求然后捕獲結果並確保您的ajax調用的結果僅按順序附加到dom。 這涉及使用$ .ajax並以某種方式添加跟蹤訂單。

這樣服務器就會盡可能快地完成它,一旦你得到它就可以按順序服務它。 或者,如果你做的事情很快,那么在緩沖區中排隊它們就沒有任何懲罰。

大多數瀏覽器可以同時處理對單個域的6個或更多個ajax請求。
http://www.browserscope.org/?category=network&v=top

如果您的腳本一次發出30個ajax請求,前6個請求將很快完成。 之后,瀏覽器可能會開始分配長達5秒的任意等待時間。 Chrome是此行為的主要示例。

請求1-6在5毫秒內返回。

請求7-12在5,005毫秒內返回。

請求11-18在10,005毫秒內返回。

請求19-24在15,005毫秒內返回。

請求25-30在20,005毫秒內返回。

我建議構建一個函數回調隊列來處理所有應用程序的ajax請求,並且一次處理不超過6個。

 var ajaxCownt = (ajaxCownt == null ? 0 : ajaxCownt); // Make limit globally accessible. var ajaxKue = (ajaxKue == null ? [] : ajaxKue); // Make queue globally accessible. function doMyAjaxRequest() { console.log("doing ajax request."); // Implement ajax request, here. } for (var i = 1;i <= 30;i++) { ajaxKue.push( function() { doMyAjaxRequest() } ); // Add request to queue. } while (ajaxCownt != null && ajaxCownt < 6 && ajaxKue != null && ajaxKue.length && ajaxKue.length > 0) { ajaxCownt++; console.log("incrementing pending ajax requests counter by 1."); ajaxKue.shift().call(); }; // Register an event to detect when an ajax request completes. // Allow for an additional ajax request to be processed. $( document ).ajaxComplete(function() { if (ajaxCownt && ajaxCownt > 0) { ajaxCownt--; console.log("decrementing pending ajax requests counter by 1."); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM