【问题标题】:Is it possible to run code after all ajax call completed under the for loop statement?在for循环语句下完成所有ajax调用后是否可以运行代码?
【发布时间】:2013-06-02 02:36:39
【问题描述】:

我有一个for循环语句,每个循环都会执行一个ajax调用。

$.each(arr, function(i, v) {
    var url = '/xml.php?id=' + v;
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'xml',
        success: function(xml) {
            if ($(xml).find('Lists').attr('total') == 1) {
                // some code here
            }
        },
        complete: function() {
            // some code here
        }
    })
})

我想在循环下allajax调用完成后运行代码,我尝试将下面的代码放在最后一行,ajax调用完成时它不执行

    if (i == arr.length - 1) {
        // some code here
    }

因此,如果我有 10 次循环,则有 10 次 ajax 调用。我想在完成 10 次 ajax 调用后运行代码,有什么想法吗?

是用.ajaxComplete()还是.done()来实现更好?

谢谢

【问题讨论】:

标签: jquery ajax each


【解决方案1】:

尝试使用$.when()

var arr = [];
$.each(arr, function(i, v) {
    var url = '/xml.php?id=' + v;
    var xhr = $.ajax({
        url: url,
        type: 'GET',
        dataType: 'xml',
        success: function(xml) {
            if ($(xml).find('Lists').attr('total') == 1) {
                // some code here
            }
        },
        complete: function() {
            // some code here
        }
    });
    arr.push(xhr);
})

$.when.apply($, arr).then(function(){
    console.log('do')
})

【讨论】:

  • 谢谢建议,但是arr.push(xhr);.apply($, arr)是什么意思呢?谢谢。
  • 如果您查看when 的文档,您会发现,一旦所有不同的对象传递给when 被解析,注册的回调就会完成。现在在这里我们必须收集由 ajax 调用创建的所有 xhr 对象,所以我使用数组来存储这些 xhr 对象,使用 arr.push(xhr);
  • 我明白了,谢谢。但是.apply($, arr)呢,这段代码是什么意思?
  • when 函数希望不同对象的列表作为不同的参数传递,例如$.when(diff1, diff2, ..., diffn),在我们的例子中,我们有一个xhr 对象的列表,.apply() 用于将数组转换为参数列表
  • 再次感谢。如果您不介意我还有一个问题...我在ajax success property 下方添加了console.log(i),我发现执行顺序不正确(例如0、1、3、2、4)。如何更改代码以使 ajax 函数按顺序执行?
【解决方案2】:

我遇到了类似的情况,但在循环内部,AJAX 调用是在另一个函数调用(称为 fetchData)中完成的。

所以我让 fetchData 函数返回来自 AJAX 调用的 Promise,并使用 then 子句将其链接起来以处理响应。

Here'sPlunker 链接

$(document).ready(function() {
  var message = '';

  process();

  function process() {
    var promises = [];
    for (var i = 0; i < 3; i++) {
      var promise;
      (function (index) {
        promise = fetchData(index).then(function (response) {
          // do something with the response.
          message += 'Iteration ' + index + '\n';
        });
      })(i);

      promises.push(promise);
    }

    $.when.apply($, promises).then(function () {
      // do something after all the AJAX calls are completed.
      alert(message);
    });
  }

  function fetchData(param) {
    return $.ajax('data.json')
      .success(fetchDataSuccess)
      .error(fetchDataFailed);

    function fetchDataSuccess(response) {
      return response;
    }

    function fetchDataFailed(error) {
      console.error(error);
    }
  }
});

【讨论】:

    猜你喜欢
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多