javascript - 等到所有 jQuery Ajax 请求都完成了吗?

标签 javascript jquery ajax

如何让一个函数等待所有 jQuery Ajax 请求在另一个函数内完成?

简而言之,我需要等待所有 Ajax 请求完成后才能执行下一个请求。但是如何呢?

最佳答案

jQuery 现在定义了一个 when function为此目的。

它接受任意数量的 Deferred 对象作为参数,并在所有对象都 resolve 时执行一个函数。

这意味着,如果您想发起(例如)四个 ajax 请求,然后在它们完成后执行一个操作,您可以这样做:

$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){
    // the code here will be executed when all four ajax requests resolve.
    // a1, a2, a3 and a4 are lists of length 3 containing the response text,
    // status, and jqXHR object for each of the four ajax calls respectively.
});

function ajax1() {
    // NOTE:  This function must return the value 
    //        from calling the $.ajax() method.
    return $.ajax({
        url: "someUrl",
        dataType: "json",
        data:  yourJsonData,            
        ...
    });
}

在我看来,它使语法清晰明了,并避免涉及任何全局变量,例如 ajaxStart 和 ajaxStop,这可能会在您的页面开发时产生不需要的副作用。

如果您事先不知道需要等待多少个 ajax 参数(即您想要使用可变数量的参数),它仍然可以完成,只是有点棘手。参见 Pass in an array of Deferreds to $.when() (也许还有 jQuery .when troubleshooting with variable number of arguments )。

如果您需要更深入地控制 ajax 脚本等的失败模式,您可以保存 .when() 返回的对象 - 它是一个 jQuery Promise包含所有原始 ajax 查询的对象。您可以对其调用 .then().fail() 以添加详细的成功/失败处理程序。

关于javascript - 等到所有 jQuery Ajax 请求都完成了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34854162/

相关文章:

javascript - 如何找到空变量并显示它

javascript - 如果我使用setInterval从数据库请求数据,会损坏服务器吗?

javascript - Leaflet.js 从 AJAX 添加层

javascript - 获取表格单元格中浮点值的总和

javascript - 在执行 Ajax 调用之前,对 DOM 的更改应该是可见的

javascript - 使用 jQuery 创建图像益智游戏

javascript 需要输入更改输入边框

javascript - jqGrid如何应用自定义过滤/搜索

jquery - css .not(this) 元素根据它的索引

javascript - 将 json 对象中每个深度级别的节点存储在单独的数组中