如何要等到jQuery的Ajax请求完成一个循环? [英] How to wait until jQuery ajax request finishes in a loop?

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

问题描述

我有code:

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

据上传图片非常好,但问题是,我无法找到一个方法来上传图片一个接一个,我试图把该选项的异步为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.

如何做到这一点?

推荐答案

您可以创建承诺的数组,这样一旦所有的承诺都解决了,你可以运行你的全部完成 code。

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天全站免登陆