如何要等到jQuery的Ajax请求完成一个循环?要等到、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,pr...

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

演示

阅读全文

相关推荐

最新文章