【问题标题】:Wait until all ajax queries in each() function are finished using $.when()等到 each() 函数中的所有 ajax 查询都使用 $.when() 完成
【发布时间】:2015-02-16 20:04:15
【问题描述】:

在检查 $.each() 函数中包含的 ajax 查询没有错误后,如何运行 callback()?

var resp_error = false;
$(".items").each(function() {
    ajax_item($(this)).done(function(resp){
        if (resp.val == 0)    return (resp_error = true);
    });
});
if (!resp_error)    callback();

其中 ajax_item(item) 是一个延迟的 ajax 查询:

function ajax_item(item) {
    return $.ajax({
       ...
    });
};

val由ajax查询返回,当val = 0时触发错误(resp_error)。

我认为最好的方法是使用$.when(),但是我没有找到编码的方法?

【问题讨论】:

  • 我有点困惑。 ajax_item 是什么?您是否尝试对每个名为 items 的项目进行 ajax 调用?
  • 这是一个ajax查询:function ajax_item(item) { return $.ajax({...});
  • 好的,我在 jQuery api 文档上,但在任何地方都没有看到。猜猜这是特别的哈哈
  • 我觉得让我很头疼的是我通常会看到一个像 $.ajax 这样的 jQuery ajax 调用。
  • 那是因为你的代码写得不好。如果我或其他人无法理解,我无法帮助您。

标签: jquery ajax .when


【解决方案1】:

最简单的方法是:

$(document).ajaxStop(function() {
  // place code to be executed on completion of last outstanding ajax call here
});

【讨论】:

  • 我相信 $.ajaxStop 会受到其他 ajax 调用的影响,而不仅仅是每个函数中的调用。
【解决方案2】:

好的,我找到了!

var resp_error = false;
var ajax_calls = [];
$(".items").each(function() {
    ajax_calls.push(ajax_item($(this)).done(function(resp){
       if (resp.val == 0)    return (resp_error = true);
    }));
});
$.when.apply($, ajax_calls).then(function() {
    if (!resp_error)    callback();
});

【讨论】:

    猜你喜欢
    • 2017-06-17
    • 2015-07-17
    • 2013-10-14
    • 2020-03-17
    • 1970-01-01
    • 2021-03-09
    相关资源
    最近更新 更多