使用 jQuery 的延迟模式 http://api.jquery.com/jQuery.when/ ,我正在尝试进行多个 jsonp ajax 调用并等待结果,然后再进行下一步。我可以使用固定数量的调用来完成此操作,因为我可以在“.done()”延迟对象中设置已解析参数的数量。但在我的应用程序中它不起作用,因为调用次数是动态的并且始终未知。
第一个简化示例之所以有效,是因为我可以在 .done() 解析函数中设置参数数量。我知道我需要两个,因为 .when() 中有两个调用:
$.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
});
感谢您对此提供的任何帮助!
最佳答案
您可以使用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)
});
关于javascript - 动态多个延迟 jQuery Ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19614354/