Wait until all jQuery Ajax requests are done?

后端 未结 21 1845
离开以前
离开以前 2020-11-21 04:39

How do I make a function wait until all jQuery Ajax requests are done inside another function?

In short, I need to wait for all Ajax requests to be done before I exe

相关标签:
21条回答
  • 2020-11-21 05:41

    jQuery now defines a when function for this purpose.

    It accepts any number of Deferred objects as arguments, and executes a function when all of them resolve.

    That means, if you want to initiate (for example) four ajax requests, then perform an action when they are done, you could do something like this:

    $.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,            
            ...
        });
    }
    

    In my opinion, it makes for a clean and clear syntax, and avoids involving any global variables such as ajaxStart and ajaxStop, which could have unwanted side effects as your page develops.

    If you don't know in advance how many ajax arguments you need to wait for (i.e. you want to use a variable number of arguments), it can still be done but is just a little bit trickier. See Pass in an array of Deferreds to $.when() (and maybe jQuery .when troubleshooting with variable number of arguments).

    If you need deeper control over the failure modes of the ajax scripts etc., you can save the object returned by .when() - it's a jQuery Promise object encompassing all of the original ajax queries. You can call .then() or .fail() on it to add detailed success/failure handlers.

    0 讨论(0)
  • 2020-11-21 05:42

    Also you could use async.js.

    I think its better than $.when because you can merge all kinds of asynchronous call that does not support promises out of the box like timeouts, SqlLite calls etc. and not just ajax requests.

    0 讨论(0)
  • 2020-11-21 05:42

    This is working for me It's very simple

    return $.ajax({
      type: 'POST',
      url: urlBaseUrl
      data: {someData:someData},
      dataType: "json",
      success: function(resultData) { 
      }
    });
    
    0 讨论(0)
提交回复
热议问题