当所有AJAX请求完成时 [英] When all AJAX requests complete

查看:42
本文介绍了当所有AJAX请求完成时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ajax请求,该请求会获取一些数据,然后将其拆分为一个数组.数组长度是可变的.

I have an ajax request that grabs some data and then splits it up into an array. The array length is variable.

  var ajax1 = $.ajax({
    url: 'myurl.php',
    type: "GET",
    dataType: "jsonp",
    success: function (data) {

      //create an array

    }

  });

一旦有了数组,我就想遍历它,并在每次迭代中运行另一个AJAX请求.我将它放在$ .when中,以确保初始ajax请求已完成:

Once I have the array, I want to loop through it and in each iteration run another AJAX request. I put it inside a $.when to make sure the initial ajax request was complete:

  $.when(ajax1).done(
    function() {

      for (i = 0; i < array.length; ++i) {

        $.ajax({
          url: 'anotherurl?=' + myarray[i],
          type: "GET",
          dataType: "jsonp",
          success: function (data) {

            //do stuff here

          }
        });

      }

    }
  )

我的问题是,当for循环完成所有AJAX请求后,如何弹出一个消息框?循环结束时,简单的 alert('complete')无效,因为AJAX是异步完成的.

My question is, how can I get a message box to pop up when the for loop has completed all the AJAX requests? A simple alert('complete') at the end of the loop won't work as the AJAX is done async.

推荐答案

您也可以通过使用 $.when 来实现.您只需要将您发出的所有AJAX请求存储在一个数组中,然后将该数组 apply()存入 $.when .试试这个:

You can achieve this by also using $.when. You just need to store all the AJAX requests you make in an array and apply() that array to $.when. Try this:

$.when(ajax1).done(function() {
    var requests = [];
    for (i = 0; i < array.length; ++i) {
        requests.push($.ajax({
            url: 'anotherurl?=' + myarray[i],
            dataType: "JSONP",
            success: function (data) {
                // do stuff here
            }
        }));
    }
    $.when.apply($, requests).done(function() {
        console.log('complete');
    });
})

您还可以通过使用 map()来稍微缩短逻辑,尽管请注意,这在<IE9.

You can also shorten the logic slightly by using map(), although be aware this won't work in < IE9.

$.when(ajax1).done(function() {
    var requests = array.map(function() {
        return $.ajax({
            url: 'anotherurl?=' + myarray[i],
            dataType: "JSONP",
            success: function (data) {
                // do stuff here
            }
        });
    });
    $.when.apply($, requests).done(function() {
        console.log('complete');
    });
})

这篇关于当所有AJAX请求完成时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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