when I have a variable number of ajax requests, how can I call them using deferreds?
my guess:
//qty_of_gets = 3;
function getHTML(productID, qty_of_gets){
var dfd = $.Deferred(),
i = 0,
c = 0;
//this is where there could be some magic to
//do multiple ajax posts
//obviously I'm out of my depth here...
while (i <= qty_of_gets){
dfd.pipe(function(){
$.get("queries/html/" + product_id + i + ".php");
});
i++
}
dfd.done(function(){
while (c <= qty_of_gets){
$('myDiv').append(c);
c++;
}
});
}
If you want to execute the Ajax calls sequentially, you have to return the promise from the callback and also attach a new callback to the last promise object:
As of jQuery 1.8, you should use
.theninstead of.pipe.Another problems is (in your example at least) that at the time the callbacks are executed,
iwon’t have the value you expect. You can use an immediately invoked function expression to capture the current value ofi. See JavaScript closure inside loops – simple practical example for more info.There is no clean solution for getting the results. I think the best you could do is adding the results to an array and access that array in the
.donecallback. I.e.: