开发者

Save the id of ajax call to use it in the return function

i have this code to populate the option in my select box(i have 7 select box in this page) with json response from the server(ajax)

for (j=1; j <= 7; j++){

            $.getJSON('mobile_json.php', {id:j}, function(data) {
                var select = $('#userAccess' + j);              
                var options = select.attr('options');
                $.each(data, function(index, array) {                   
                    options[array['Id']] = new Option(array['Name']);
                });  
            });  
    }   

The problem is after开发者_JS百科 the calling to the ajax, the j equal to 8 , what i want is when the function deal with the json array, is set it to the right select box like : userAccess1 , userAccess2 ... userAccess7,

how can i deal with it?


It is because you are creating closures in a loop. This helped me to understand it better (especially example 5).

One way to solve this is to create an anonymous function and execute it immediately :

for (j=1; j <= 7; j++){
    (function(index) {
        $.getJSON('mobile_json.php', {id:index}, function(data) {
            var select = $('#userAccess' + index);              
            var options = select.attr('options');
            $.each(data, function(index, array) {                   
                options[array['Id']] = new Option(array['Name']);
            });  
        });
     })(j)
 }  

This "captures" the current value of j. If you don't do this, by the time the closure (the callback function to the Ajax request) is executed, the loop is already finished, leaving j with the value of 8.
That's the tricky thing about closures :)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜