[英]How to wait until jQuery ajax request finishes in a loop?
我有那个代码:
for (var i = 0; i < $total_files; i++) {
$.ajax({
type: 'POST',
url: 'uploading.php',
context: $(this),
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: data_string,
success: function(datas) {
//does something
},
error: function(e) {
alert('error, try again');
}
});
}
它上传的图片非常好,但问题是我找不到逐个上传图片的方法,我试图将选项async设置为false但它冻结了网页浏览器,直到所有图片都上传不是我的想要,我想以某种方式模拟这个“async:false”选项来执行相同的操作但不冻结Web浏览器。
这该怎么做 ?
您可以创建一个承诺数组,以便在解决所有承诺后,您可以运行all done
代码。
var promises = [];
for (var i = 0; i < $total_files; i++){
/* $.ajax returns a promise*/
var request = $.ajax({
/* your ajax config*/
})
promises.push( request);
}
$.when.apply(null, promises).done(function(){
alert('All done')
})
使用每个调用填充数组,并在完成上一个调用后调用下一个项目。
你可以尝试这样的事情:
window.syncUpload = {
queue : [],
upload : function(imagesCount) {
var $total_files = imagesCount, data_string = "";
/* Populates queue array with all ajax calls you are going to need */
for (var i=0; i < $total_files; i++) {
this.queue.push({
type: 'POST',
url: 'uploading.php',
context: $(this),
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: data_string,
success: function(datas) {
//does something
},
error: function(e){
alert('error, try again');
},
/* When the ajax finished it'll fire the complete event, so we
call the next image to be uploaded.
*/
complete : function() {
this[0].uploadNext();
}
});
}
this.uploadNext();
},
uploadNext : function() {
var queue = this.queue;
/* If there's something left in the array, send it */
if (queue.length > 0) {
/* Create ajax call and remove item from array */
$.ajax(queue.shift(0));
}
}
}
只需使用syncUpload.upload(NUMBER_OF_IMAGES)调用它;
对于jQuery 3.x +和支持本机Promise
现代浏览器, Promise.all
可以这样使用:
var promises = [];
for (var i = 0; i < $total_files; i++) {
// jQuery returns a prom
promises.push($.ajax({
/* your ajax config*/
}))
}
Promise.all(promises)
.then(responseList => {
console.dir(responseList)
})
如果您的文件已经存储在列表中,那么您可以使用map
而不是循环。
var fileList = [/*... list of files ...*/];
Promise.all(fileList.map(file => $.ajax({
/* your ajax config*/
})))
.then(responseList => {
console.dir(responseList)
})
我会尝试jQuery.when所以你仍然可以使用异步调用但延迟,如:
jQuery(document).ready(function ($) {
$.when(
//for (var i = 0; i < $total_files; i++) {
$.ajax({
// ajax code
})
//}
).done(function () {
// perform after ajax loop is done
});
}); // ready
编辑 :ajax迭代应该在$.when
.when之外完成并按照charlietfl的回答推荐到数组中。 您可以使用(异步)ajax调用并将其推迟到$.when
.when中,但请参阅JSFIDDLE
在jquery的一个声明中
$.when.apply(null, $.map(/*input Array|jQuery*/, function (n, i) {
return $.get(/* URL */, function (data) {
/* Do something */
});
})).done(function () {
/* Called after all ajax is done */
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.