[英]How to detect when processing is finished for multiple ajax calls in javascript?
Assuming I have the following: 假设我有以下内容:
function main() {
var finished = false;
for(var i=0; i < 3; i++) {
do(i);
}
}
function do(i) {
$.ajax({
url:"myurl.com/"+i,
datatype:"text/xml",
success: function() {
// Two more layers of multiple nested $.ajax elements here
}
})
}
Is there some way I could pop an alert box after all the "do" are finished after the three iterations? 在三次迭代完成所有“do”之后,是否有某种方法可以弹出警报框? How? 怎么样? Syntax would help. 语法会有所帮助。
An ajax call returns a jQuery Promise object. ajax调用返回一个jQuery Promise对象。 You could collect the output of each one in an array, and use $.when
to 'bundle' the promises together. 你可以收集数组中每个的输出,并使用$.when
将promises“捆绑”在一起。
This code is the basic idea behind what you want: 此代码是您想要的基本理念:
function main() {
var finished = false;
var defs = [];
for(var i=0; i < 3; i++) {
defs.push(do(i));
}
$.when.apply(null, defs).done(function() {
//this code will only run when all ajax calls are complete
});
}
function do(i) {
var promise = $.ajax({
url:"myurl.com/"+i,
datatype:"text/xml",
success: function() {
// Two more layers of multiple nested $.ajax elements here
}
})
return promise;
}
The browser can have a lot of open HTTP connections, don't let the naysayers convince you otherwise. 浏览器可以有很多开放的HTTP连接,不要让反对者说服你。 Here is a table of maximum concurrent connections supported by browser. 以下是浏览器支持的最大并发连接数表。 Let your site usage statistics be your guide, but even 2 ajax requests at once is faster than totally synchronous data requests... 让您的网站使用情况统计数据成为您的指南,但即使是2个ajax请求也会比完全同步的数据请求更快...
Firefox 2: 2
Firefox 3+: 6
Opera 9.26: 4
Opera 12: 6
Safari 3: 4
Safari 5: 6
IE 7: 2
IE 8: 6
IE 10: 8
Chrome: 6
As global: 全球:
var complete = 0;
All AJAX calls; 所有AJAX电话;
$.ajax({
... //other attributes,
complete: function(){
complete++;
if (complete == 3) {
alert('all completed');
}
}
});
This would execute when three AJAX calls are done. 这将在完成三个AJAX调用时执行。 However, if you need to increase it, then do so. 但是,如果您需要增加它,那么这样做。
You can use an array of statuses for this: 您可以使用以下状态数组:
function main() {
var ready = new Array(3);
for (var i = 0; i < 3; i++) {
ready[i] = false;
}
for (var i = 0; i < 3; i++) {
do(i, ready);
}
}
function do(i, ready) {
$.ajax({
url:"myurl.com/"+i,
datatype:"text/xml",
success: function() {
// If there are multiple layers then the next statements should be executed in the last layer.
ready[i] = true;
if (isAllReady(ready)) {
alert("All done!");
}
}
})
}
function isAllReady(ready) {
var allReady = true;
for (var i = 0; i < 3; i++) {
if (!ready[i]) {
allReady = false;
}
}
return allReady;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.