开发者

Multiple ajax requests in jQuery with many arguments in $.when method

开发者 https://www.devze.com 2023-03-18 07:23 出处:网络
Can I make multiples jquery ajax requests with the $.when method, without knowing the number of arguments?

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)

0

精彩评论

暂无评论...
验证码 换一张
取 消