【问题标题】:Array in success function undefined成功函数中的数组未定义
【发布时间】:2011-09-27 05:05:06
【问题描述】:

为什么会有这段代码

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

我该如何解决这个问题?

【问题讨论】:

    标签: javascript jquery ajax arrays


    【解决方案1】:

    由于闭包的工作方式,i 的值在回调中总是等于array.length,因为这就是循环完成后的值(毕竟,i &lt; array.length 是假的)。而且那个位置总是不确定的。您需要在循环内重新绑定 i 以使当前值“粘住”。不幸的是,在标准 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
    }
    

    【讨论】:

    • 正确,稍作修正:i 不保证在每次回调时都是array.length。这是不可预测的,取决于触发回调的时间,即 Ajax 响应何时到来。
    • @Mike:异步响应处理程序与其他所有内容在同一个线程中运行,通过与其他所有内容相同的事件队列。在循环(以及整个当前事件处理程序)被完全处理之前,不会运行任何响应处理程序。
    • 如果OP在循环之后直接访问数组,他也不会看到任何区别。
    【解决方案2】:

    您可以进行同步调用:

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

    希望这会有所帮助。干杯

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      • 2021-08-10
      • 2021-10-06
      • 1970-01-01
      • 2012-06-21
      • 2023-02-21
      • 1970-01-01
      相关资源
      最近更新 更多