Multiple ajax calls from array and handle callback when completed

前端 未结 2 452
别那么骄傲
别那么骄傲 2020-12-05 02:58

I have used promises in jQuery slightly before - but I am having trouble applying it to this scenario. I prefer to use the $.when() and $.done() methods to achieve this.

相关标签:
2条回答
  • 2020-12-05 03:38

    I share an easy example that could help you to handle multiple requests and their responses:

    var arr = [
        $.ajax({url:"test1.php"}),
        $.ajax({url:"test2.php"}),
        $.ajax({url:"test3.php"})
    ];
    $.when.apply( undefined, arr ).then(function() {
        var objects=arguments;
        console.dir(objects);
    });
    
    0 讨论(0)
  • 2020-12-05 03:44

    The arguments to $.when should be the return value of $.ajax, which also doesn't need to be called separately -- that makes no sense. You want something like this:

    for (i = 0; i < list.length; i++) {
       requests.push($.ajax(...));
    }
    $.when.apply(undefined, requests).then(...)
    

    The reason that .apply is needed is because $.when can take multiple arguments, but not an array of arguments. .apply expands essentially to:

    $.when(requests[0], requests[1], ...)
    

    This also assumes that the requests can be completed in any order.

    http://jsfiddle.net/MBZEu/4/ -- notice that 'done' is logged to the console after all of the success messages.

    0 讨论(0)
提交回复
热议问题