Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic multiple Deferred jQuery Ajax calls

Using the Deferred pattern from jQuery http://api.jquery.com/jQuery.when/, I am trying to make multiple jsonp ajax calls and wait for the results before moving to the next step. I can accomplish this using a fixed amount of calls because I can set the number of resolved argument parameters in the ".done()" deferred object. But in my application it doesn't work because the number of calls is dynamic and always unknown.

This first simplified example works because I can set the number of args in the .done() resolved function. I know I need two because there are two calls in the .when():

$.when( $.ajax( url1 ), $.ajax( url2 ) ).done(function( a1, a2 ) {       var data = a1[ 0 ] + a2[ 0 ];  }); 

This is what I need but can't get it to work:

var urls = GetUrlList(); // returns array of urls to json service var requests = []; // hold ajax request for (i = 0; i < urls.length; i++) {     requests.push($.ajax(url[i])); }  $.when.apply($, requests).done(function ("what goes here?") {     // Need to get the data returned from all ajax calls here }); 

Thanks for any help on this!

like image 918
Xay Xayay Avatar asked Oct 27 '13 03:10

Xay Xayay


1 Answers

You can use arguments, which is a special king of object holding all arguments passed to a function

$.when.apply($, requests).done(function () {     console.log(arguments); //it is an array like object which can be looped     var total = 0;     $.each(arguments, function (i, data) {         console.log(data); //data is the value returned by each of the ajax requests          total += data[0]; //if the result of the ajax request is a int value then     });      console.log(total) }); 
like image 103
Arun P Johny Avatar answered Sep 21 '22 21:09

Arun P Johny