【发布时间】:2009-06-06 13:33:14
【问题描述】:
我想在 jQuery 中发出 X 个 ajax 请求并将 json 响应添加到数组中。 当所有 ajax 请求都完成后,我想执行一些代码。有什么好办法解决吗?
【问题讨论】:
我想在 jQuery 中发出 X 个 ajax 请求并将 json 响应添加到数组中。 当所有 ajax 请求都完成后,我想执行一些代码。有什么好办法解决吗?
【问题讨论】:
除了将请求计数并在您的代码中手动重新计数之外,我不知道任何其他方法。一旦他们都回来了,就执行你的主回调。
【讨论】:
这段代码应该做你想做的,所有的jQuery风格。基本上它使用一些递归来完成它。将选项传递给 loadmultiples 函数以设置您想要执行的操作,并将 JSON 响应推送到数组中。如果您想将 JSON 响应合并到一个结构中,您可以轻松更改它,但我不确定这是否是您想要的。
var loadmultiples = function(options) {
var settings = $.extend({
//set the url to get
url : '/response.json',
//this function is called when everything is done
callback : function() {},
//set this option to define how many loads to do
numbertodo : 10,
//these two are just used for
//storing data while we recurse,
//and keeping track of the current position
//however you can change them if you want to start
//from a different point, or have existing data
numberdone : 0,
data : []
}, options || {});
//load the json, passing up the current 'number'
//of the content to load
$.ajax({
url : settings.url,
data : { 'number' : settings.numberdone },
dataType: 'json',
success: function(result) {
//add the response to the data
settings.data.push(result);
//increment the counter of how many files have been done
settings.numberdone++;
//
if(settings.numberdone < settings.numbertoexecute) {
loadmultiples(settings);
} else {
settings.callback(settings.data);
}
}
});
}
//so now we can call it...
loadmultiples({
callback: function(data) {
//this function will get called when all the data calls have been
//completed, and the resulting data is in the data parameter
}
});
【讨论】:
对于每个 ajax 响应我会做:
for(var k in json) 一些数组[k]=json[k];
但我不确定您的 json 数据看起来如何。
【讨论】:
我最近通过触发一堆 ajax 请求来做到这一点,然后在它们进入时递减一个计数器。
它工作得很好,但我最终将我的代码从一堆小的 ajax 请求更改为一次向服务器询问所有内容。更少的请求和更少的开销,并且更加健壮。
除非您有充分的理由提出单独的请求(有些请求可能很快,有些请求很慢,并且您可以在收到的信息中提供一些有意义的信息显示),否则我会将它们放在一起(假设您可以修改服务器代码或添加新的服务器代码)。
【讨论】: