2013-06-26 60 views
3

我需要做一些Ajax調用(確切的數字是變量),並等待他們完成。我目前的代碼如下:jQuery使動態Ajax調用,並等待他們完成

ajaxRequests = new Array(); 

ajaxRequests.push(function(){ 
       return jQuery.post(url: "someUrl", 
            dataType: "json", 
            data: yourJsonData 
      }); 



jQuery.when.apply(jQuery, ajaxRequests).done(function(){ 
    alert("ajax requests done"); 
}); 

不幸的是,上面的代碼並沒有等待ajax請求完成。任何幫助將被認識。

+1

檢查複製如果以下的答案可以幫助你http://stackoverflow.com/questions/9865586/jquery-when-troubleshooting-with-variable-number- of-arguments – mrida

+0

確保在yourJsonData之後關閉括號。這可能會導致問題 – mrida

回答

4

答案是如下:從jQuery .when troubleshooting with variable number of arguments

// Array of requests 
var requests = Array(); 
requests.push($.get('responsePage.php?data=foo')); 
requests.push($.get('responsePage.php?data=bar')); 

var defer = $.when.apply($, requests); 
defer.done(function(){ 

    // This is executed only after every ajax request has been completed 

    $.each(arguments, function(index, responseData){ 
     // "responseData" will contain an array of response information for each specific request 
    }); 

}); 
+1

當您至少有兩個請求發送時,這可以很好地工作。否則,當它是一個查詢或幾個時,會出現不一致的行爲:( – Happynoff