2013-10-27 80 views
22

從jQuery http://api.jquery.com/jQuery.when/使用延遲模式,我試圖做出多個jsonp ajax調用並等待結果,然後再轉到下一步。我可以使用固定數量的調用完成此操作,因爲我可以在「.done()」延遲對象中設置已解析參數的數量。但在我的應用程序中,它不起作用,因爲通話次數是動態的,並且始終未知。動態多個延期jQuery Ajax調用

這是第一個簡化的例子,因爲我可以設置.done()解析函數中的參數個數。我知道我需要兩個,因爲有在。當兩個調用():

$.when($.ajax(url1), $.ajax(url2)).done(function(a1, a2) { 
    var data = a1[ 0 ] + a2[ 0 ]; 
}); 

這是我需要的,但不能讓它開始工作:

var urls = GetUrlList(); // returns array of urls to json service 
var requests = []; // hold ajax request 
for (i = 0; i < urls.length; i++) { 
    requests.push($.ajax(url[i])); 
} 

$.when.apply($, requests).done(function ("what goes here?") { 
    // Need to get the data returned from all ajax calls here 
}); 

感謝您的幫助上這個!

回答

30

您可以使用arguments,這是對象持有傳遞給函數

$.when.apply($, requests).done(function() { 
    console.log(arguments); //it is an array like object which can be looped 
    var total = 0; 
    $.each(arguments, function (i, data) { 
     console.log(data); //data is the value returned by each of the ajax requests 

     total += data[0]; //if the result of the ajax request is a int value then 
    }); 

    console.log(total) 
}); 
+0

感謝那些所有工作參數的特殊的王! –

+0

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

+0

參數鏈接已過時並指向已棄用的功能。[已更新的鏈接是此](https://developer.mozilla.org/zh-cn) US/docs/Web/JavaScript/Reference/Functions/arguments) – Liam