jQuery callback for multiple ajax calls

后端 未结 14 1960
夕颜
夕颜 2020-11-22 09:18

I want to make three ajax calls in a click event. Each ajax call does a distinct operation and returns back data that is needed for a final callback. The calls themselves ar

14条回答
  •  佛祖请我去吃肉
    2020-11-22 09:57

    It's worth noting that since $.when expects all of the ajax requests as sequential arguments (not an array) you'll commonly see $.when used with .apply() like so:

    // Save all requests in an array of jqXHR objects
    var requests = arrayOfThings.map(function(thing) {
        return $.ajax({
            method: 'GET',
            url: 'thing/' + thing.id
        });
    });
    
    $.when.apply(this, requests).then(function(resp1, resp2/*, ... */) {
        // Each argument is an array with the following structure: [ data, statusText, jqXHR ]
        var responseArgsArray = Array.prototype.slice.call(this, arguments);
    
    });
    

    Using the Spread syntax, you can now write this code like so:

    $.when(...requests).then((...responses) => {
        // do something with responses
    })
    

    This is because $.when accepts args like this

    $.when(ajaxRequest1, ajaxRequest2, ajaxRequest3);
    

    And not like this:

    $.when([ajaxRequest1, ajaxRequest2, ajaxRequest3]);
    

提交回复
热议问题