Multiple ajax requests in jQuery with many arguments in $.when method
Can I make multiples jquery ajax requests with the $.when
method, without knowing the number of arguments?
This is my code:
var ajax_loaded = new Array();
$('.chart input[name^="qtd"]').each(function()
{
ajax_loaded.push(function(){$.ajax({
开发者_JAVA百科 url : www + 'chart/add',
type : 'POST',
data : {
qtde: $(this).val(),
idProd: $(this).prev().val()
}
})});
});
$.when(ajax_loaded ).done(function(){
alert('Done');
});
Yes - use Function.apply
to call $.when()
with your array of unknown length:
var ajax_loaded = [];
$('.chart input[name^="qtd"]').each(function()
{
ajax_loaded.push($.ajax({
url : www + 'chart/add',
type : 'POST',
data : {
qtde: $(this).val(),
idProd: $(this).prev().val()
}
});
});
$.when.apply($, ajax_loaded ).done(function(){
alert('Done');
});
NB: note that you need to push the result of $.ajax
into the array, not a function. Pushing a closure won't work.
Depending on what you're doing it might be easier to use the .ajax() callbacks (success and error)
精彩评论