开发者

jQuery: How do I pass a value into an Ajax call?

I am updating some div as follows:

for(var i = 0; i < data.length; i++) {
    var query = base_url + data[i];
    $.ajax({
        url: query,
        type: 'GET',
        dataType: 'jsonp',
        timeout: 2000,
        error: function() { self.html("Network Error"); },
        success: function(json) {
            $("#li" + i).html("<img src='" + json.result.list[0].url + "' />")
        }
    });
}

The value of i does not work inside the ajax call. I am trying to pass the value of i so that it can attach the element to the proper 开发者_C百科div. Can someone help me out?


Ok. This works but would really love if someone can explain it! I broke my head over this so posting it here just in case someone needs it.

for(i = 0; i < data.length; i++)
   fetchItem(i)

fetchItem = function(i) {
    var query = base_url + data[i]; 
    $.ajax({ 
        url: query, 
        type: 'GET', 
        dataType: 'jsonp', 
        timeout: 2000, 
        error: function() { self.html("Network Error"); }, 
        success: function(json) { 
            $("#li" + i).html("<img src='" + json.result.list[0].url + "' />") 
        } 
    }); 
}


Have you tried making i a global variable:

Change:

for(var i = 0; i < data.length; i++) { 
    var query = base_url + data[i]; 
    $.ajax({ 
        url: query, 
        type: 'GET', 
        dataType: 'jsonp', 
        timeout: 2000, 
        error: function() { self.html("Network Error"); }, 
        success: function(json) { 
            $("#li" + i).html("<img src='" + json.result.list[0].url + "' />") 
        } 
    }); 
} 

To this:

for(i = 0; i < data.length; i++) { 
    var query = base_url + data[i]; 
    $.ajax({ 
        url: query, 
        type: 'GET', 
        dataType: 'jsonp', 
        timeout: 2000, 
        error: function() { self.html("Network Error"); }, 
        success: function(json) { 
            $("#li" + i).html("<img src='" + json.result.list[0].url + "' />") 
        } 
    }); 
} 

Also I agree with Nick. You can do the looping first then send the array (JSON) serverside to be processed. This way the application will be much more responsive.


I think your problem has to do with scope.

You should wrap the what's in the for loop into a function

for(var i = 0; i < data.length; i++) {
   doAjax(i);
}

function doAjax(i) {
 var query = base_url + data[i];
    $.ajax({
        url: query,
        type: 'GET',
        dataType: 'jsonp',
        timeout: 2000,
        error: function() { self.html("Network Error"); },
        success: function(json) {
            $("#li" + i).html("<img src='" + json.result.list[0].url + "' />")
        }
    });
}

The i value for the closure function of success is correctly bound only when it is not in a for loop.

That should work. Good luck.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜