Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

jQuery ajax inside a loop problem

This js loop script always get the last value of ui_item inside a jquery ajax funciton. How can a catch the correct value of each iteration?

for (var i = 0; i <= split_files_cb_value_holder.length - 1; i++){
    var split_values = split_files_cb_value_holder[i].split(':');

    ui_item = split_files_cb_value_holder[i];

    $.ajax({
        type: "POST",
        url: "ds/index.php/playlist/check_folder",
        data: "component_type="+$('#component_type').val()+"&value="+split_values[1],
        success: function(msg)
        {
            console.log(ui_item); //ALWAYS GETS THE LAST VALUE
        },
        error: function()
        {
            alert("An error occured while updating. Try again in a while");
        }
    });

}

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that the anonymous callback method captures the ui_item variable by reference. Since there is only one variable, it always gets whatever was assigned last to the variable.

You need to wrap the contents of the for loop in a function that takes i as a parameter, then call the function in the loop. Each call to the wrapper function will create a separate variable, solving the problem.

For example:

function doCheck(i) {
    var split_values = split_files_cb_value_holder[i].split(':');

    var ui_item = split_files_cb_value_holder[i];

    $.ajax({
        type: "POST",
        url: "ds/index.php/playlist/check_folder",
        data: "component_type="+$('#component_type').val()+"&value="+split_values[1],
        success: function(msg)
        {
            console.log(ui_item); //Don't always get the last value
        },
        error: function()
        {
            alert("An error occured while updating. Try again in a while");
        }
    });
}

for (var i = 0; i < split_files_cb_value_holder.length; i++) 
    doCheck(i);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...