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

简而言之,在执行下一个Ajax请求之前,我需要等待所有Ajax请求都完成。但如何?


当前回答

使用ajaxStop事件。

例如,假设你有一个载入…消息,同时获取100个ajax请求,你想隐藏该消息一旦加载。

jQuery文档:

$("#loading").ajaxStop(function() {
  $(this).hide();
});

请注意,它将等待所有ajax请求在该页面上完成。

其他回答

美元。当不为我工作时,回调(x)而不是返回x工作如下所述:https://stackoverflow.com/a/13455253/10357604

使用ajaxStop事件。

例如,假设你有一个载入…消息,同时获取100个ajax请求,你想隐藏该消息一旦加载。

jQuery文档:

$("#loading").ajaxStop(function() {
  $(this).hide();
});

请注意,它将等待所有ajax请求在该页面上完成。

jQuery现在为此定义了一个when函数。

它接受任意数量的Deferred对象作为参数,并在所有这些对象都解析时执行函数。

这意味着,如果你想发起(例如)四个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参数(即你想使用可变数量的参数),它仍然可以完成,只是有点棘手。参见在一个数组中传递deferred to $.when()(也可以是jQuery .当使用可变参数进行故障排除时)。

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

Javascript是基于事件的,所以你不应该等待,而应该设置钩子/回调

你可以只使用jquery.ajax的success/complete方法

或者你可以使用。ajaxcomplete:

$('.log').ajaxComplete(function(e, xhr, settings) {
  if (settings.url == 'ajax/test.html') {
    $(this).text('Triggered ajaxComplete handler.');
    //and you can do whatever other processing here, including calling another function...
  }
});

虽然你应该张贴一个伪代码你的(s) ajax请求(s)是(是)被调用更精确…

当所有ajax加载完成时,我使用大小检查

function get_ajax(link, data, callback) { $.ajax({ url: link, type: "GET", data: data, dataType: "json", success: function (data, status, jqXHR) { callback(jqXHR.status, data) }, error: function (jqXHR, status, err) { callback(jqXHR.status, jqXHR); }, complete: function (jqXHR, status) { } }) } function run_list_ajax(callback){ var size=0; var max= 10; for (let index = 0; index < max; index++) { var link = 'http://api.jquery.com/ajaxStop/'; var data={i:index} get_ajax(link,data,function(status, data){ console.log(index) if(size>max-2){ callback('done') } size++ }) } } run_list_ajax(function(info){ console.log(info) }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>