如何等待 jQuery ajax 请求在循环中完成? [英] How to wait until jQuery ajax request finishes in a loop?

查看:43
本文介绍了如何等待 jQuery ajax 请求在循环中完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有那个代码:

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" 选项来执行同样的事情,但不冻结网络浏览器.

It uploads images very well but the problem is that I can't find a way to upload the images one by one, I tried to put the option async to false but it freezes the web browser until all images are uploaded which is not what I want, I want to emulate somehow this "async : false" option to perform the same thing but without freezing the web browser.

如何做到这一点?

推荐答案

您可以创建一个 Promise 数组,以便在所有 Promise 都得到解决后,您就可以运行 all done 代码.

You can create an array of promises so that once all promises are resolved you can run your all done code.

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')
})

演示

这篇关于如何等待 jQuery ajax 请求在循环中完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆