nodisplayname
nodisplayname

Reputation: 15

Ajax with arrays and for loop

I want to ajax an array of urls, like this

var urls = [url1, url2, url3];
var ids = [id1, id2, id3];

function test() {
        for(var i = 0 ; i<urls.length; i++){
        $.ajax({
          url: **urls[i]**,
          type:'POST',
          success: function(data){
             $('**ids[i]**').html($(data).find('.....').text());
          }
        });
       }
    }

For 1 url i want to use 1 id ex:ids[0] = urls[0] ....

Upvotes: 0

Views: 50

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You can't access i inside the success handler because it is a closure variable updated in a loop, which will give you wrong results...

so try

var urls = [url1, url2, url3];
var ids = [id1, id2, id3];

function test() {
    $.each(urls, function (i, url) {
        $.ajax({
            url: url,
            type: 'POST',
            success: function (data) {
                //make sure the ids has `#` prefix 
                $(ids[i]).html($(data).find('.....').text());
            }
        });
    });
}

Upvotes: 3

Related Questions