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

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


当前回答

一个小小的变通方法是这样的:

// Define how many Ajax calls must be done
var ajaxCalls = 3;
var counter = 0;
var ajaxCallComplete = function() {
    counter++;
    if( counter >= ajaxCalls ) {
            // When all ajax calls has been done
        // Do something like hide waiting images, or any else function call
        $('*').css('cursor', 'auto');
    }
};

var loadPersons = function() {
        // Show waiting image, or something else
    $('*').css('cursor', 'wait');

    var url = global.ctx + '/loadPersons';
    $.getJSON(url, function(data) {
            // Fun things
    })
    .complete(function() { **ajaxCallComplete();** });
};

var loadCountries = function() {
    // Do things
    var url = global.ctx + '/loadCountries';
    $.getJSON(url, function(data) {
            // Travels
    })
    .complete(function() { **ajaxCallComplete();** });
};

var loadCities = function() {
    // Do things
    var url = global.ctx + '/loadCities';
    $.getJSON(url, function(data) {
            // Travels
    })
    .complete(function() { **ajaxCallComplete();** });
};

$(document).ready(function(){
    loadPersons();
    loadCountries();
    loadCities();
});

希望能有用…

其他回答

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

我的解决方案如下

var request;
...
'services': {
  'GetAddressBookData': function() {
    //This is the primary service that loads all addressbook records 
    request = $.ajax({
      type: "POST",
      url: "Default.aspx/GetAddressBook",
      contentType: "application/json;",
      dataType: "json"
    });
  },

  ...

  'apps': {
    'AddressBook': {
      'data': "",
      'Start': function() {
          ...services.GetAddressBookData();
          request.done(function(response) {
            trace("ajax successful");
            ..apps.AddressBook.data = response['d'];
            ...apps.AddressBook.Filter();
          });
          request.fail(function(xhr, textStatus, errorThrown) {
            trace("ajax failed - " + errorThrown);
          });

工作得很顺利。我已经尝试了许多不同的方法,但我发现这是最简单和最可重用的方法。希望能有所帮助

正如其他答案所提到的,你可以使用ajaxStop()等待直到所有ajax请求完成。

$(document).ajaxStop(function() {
     // This function will be triggered every time any ajax request is requested and completed
});

如果你想为特定的ajax()请求做这件事,你能做的最好的是在特定的ajax请求中使用complete()方法:

$.ajax({
    type: "POST",
    url: "someUrl",
    success: function(data) {
        // This function will be triggered when ajax returns a 200 status code (success)
    },
    complete: function() {
        // This function will be triggered always, when ajax request is completed, even it fails/returns other status code
    },
    error: function() {
        // This will be triggered when ajax request fail.
    }
});

但是,如果你只需要等待几个和特定的ajax请求被完成?使用美妙的javascript承诺等待,直到这些ajax你想等待完成。我做了一个简单易读的示例,向您展示promises如何与ajax一起工作。请看下一个例子。我使用setTimeout来阐明这个示例。

// Note: // resolve() is used to mark the promise as resolved // reject() is used to mark the promise as rejected $(document).ready(function() { $("button").on("click", function() { var ajax1 = new Promise((resolve, reject) => { $.ajax({ type: "GET", url: "https://miro.medium.com/max/1200/0*UEtwA2ask7vQYW06.png", xhrFields: { responseType: 'blob'}, success: function(data) { setTimeout(function() { $('#image1').attr("src", window.URL.createObjectURL(data)); resolve(" Promise ajax1 resolved"); }, 1000); }, error: function() { reject(" Promise ajax1 rejected"); }, }); }); var ajax2 = new Promise((resolve, reject) => { $.ajax({ type: "GET", url: "https://cdn1.iconfinder.com/data/icons/social-media-vol-1-1/24/_github-512.png", xhrFields: { responseType: 'blob' }, success: function(data) { setTimeout(function() { $('#image2').attr("src", window.URL.createObjectURL(data)); resolve(" Promise ajax2 resolved"); }, 1500); }, error: function() { reject(" Promise ajax2 rejected"); }, }); }); var ajax3 = new Promise((resolve, reject) => { $.ajax({ type: "GET", url: "https://miro.medium.com/max/632/1*LUfpOf7teWvPdIPTBmYciA.png", xhrFields: { responseType: 'blob' }, success: function(data) { setTimeout(function() { $('#image3').attr("src", window.URL.createObjectURL(data)); resolve(" Promise ajax3 resolved"); }, 2000); }, error: function() { reject(" Promise ajax3 rejected"); }, }); }); Promise.all([ajax1, ajax2, ajax3]).then(values => { console.log("We waited until ajax ended: " + values); console.log("My few ajax ended, lets do some things!!") }, reason => { console.log("Promises failed: " + reason); }); // Or if you want wait for them individually do it like this // ajax1.then(values => { // console.log("Promise 1 resolved: " + values) // }, reason => { // console.log("Promise 1 failed: " + reason) // }); }); }); img { max-width: 200px; max-height: 100px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button>Make AJAX request</button> <div id="newContent"> <img id="image1" src=""> <img id="image2" src=""> <img id="image3" src=""> </div>

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()来添加详细的成功/失败处理程序。

如果你需要简单的东西;Once and done回调

        //multiple ajax calls above
        var callback = function () {
            if ($.active !== 0) {
                setTimeout(callback, '500');
                return;
            }
            //whatever you need to do here
            //...
        };
        callback();