成功函数数组未定义

时间:2011-07-02 08:41:27

标签: javascript jquery ajax arrays

为什么这段代码

for(var i = 0; i < array.length; ++i) {
    array[i]["bla"] = "check";
}

完美地工作,而阵列在这里,根据萤火虫,未定:

for(var i = 0; i < array.length; ++i) {
    $.ajax({
        type: "POST",
        url: "my url",
        data: "data here",
        success: function() {
            array[i]["bla"] = "check";
        }
    });
}

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

由于闭包的工作原理,i的值总是等于回调中的array.length,因为在循环完成之后它是等于的(毕竟,i < array.length是假的。而且这个位置总是未定义的。您需要在循环内重新绑定i以使当前值&#34;坚持&#34;。不幸的是,在标准JS中执行此操作的唯一方法是使用另一个函数,例如:

for (...; i++) {
    (function(boundI) {
        // boundI is now bound to the current value of i in the current scope
        // If you want, you can call boundI just "i", but make sure you understand
        // how scopes work in JS before you do.
        $.ajax({
            ...
            success: function() {
                array[boundI]["bla"] = "check";
            }
        });
    })(i); // pass in the current value of the loop index which gets bound to boundI
}

答案 1 :(得分:0)

您可以进行同步通话:

for(var i = 0; i < array.length; ++i) {
    $.ajax({
        type: "POST",
        async: false, //This does the magic
        url: "my url",
        data: "data here",
        success: function() {
            array[i]["bla"] = "check";
        }
    });
}

或者,保持同步性

    var array = ...    
    function loadElement(i){
       if(i == array.length) return;
       $.ajax({
            type: "POST",
            url: "my url",
            data: "data here",
            success: function() {
                array[i]["bla"] = "check";
                loadElement(i+1); 
            }
        });
    }
    loadElement(0);

希望这会有所帮助。干杯