jQuery的AJAX内部循环问题 [英] jQuery ajax inside a loop problem

查看:219
本文介绍了jQuery的AJAX内部循环问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个js脚本循环总能得到一个jQuery的AJAX功能可按内部ui_item的最后一个值。如何才能赶上每个迭代的正确的价值?

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");
        }
    });

}

谢谢!

推荐答案

问题是,匿名回调方法参照捕捉 ui_item 变量。因为有上;Ý一个变量,它总是得到任何最后被分配到变量

The problem is that the anonymous callback method captures the ui_item variable by reference. Since there is on;y 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.

例如:

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);

这篇关于jQuery的AJAX内部循环问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆