jQuery getJson()的非常奇怪的行为不会改变循环中的值

时间:2010-10-16 05:11:15

标签: javascript jquery

好的,这个问题很奇怪。我正在使用getJSON()收到一个项目列表。对于每个返回的项目,我再次使用getJSON()执行查找。在返回第二次查找时,我尝试将一个变量从for循环的范围附加到DOM,但输出是SAME。奇怪的是,当我在第二个getJSON()之前发出变量的alert()时,变量就会发生变化。

这是一个错误吗?似乎getJSON正在缓存一些东西......

$.getJSON(
"http://someurl", 
    function(data) {
        var items = data.items;

        for(i=0; i<items.length; i++) {
            var i = items[i];
            //when doing an alert of 'i' here, it changes...
            $.getJSON(
                "http://anotherurl",
                    function(r) {
                        $("#feed").append(i.some_property); 
                        //appended item should be different upon each loop
                        //but ends up appending the same thing every time!!
                    }
            )
        }
    }
)

2 个答案:

答案 0 :(得分:4)

Ajax是异步的。

在内部getJSON发出的第一个HTTP请求返回之前,您可能会设法在外部循环中循环,因此i位于内部回调首次运行之前的最后一个值上。

当您添加alert时,循环执行将暂停,直到您单击“确定”按钮,这会给HTTP请求提供响应时间。

您需要在不同的范围内创建新的i(或其他变量)。

for(var i=0; i<items.length; i++) {
     // IMPORTANT: Don't forget to use var. 
     // DO NOT use globals without a very good reason
     // Oh, i is a var but you use the keyword on the *second* time you use it
     // Don't do that, it's confusing!
     do_the_inside_thing(items[i]);
}

function do_the_inside_thing(foo) {
    // A new function is a new scope
        $.getJSON(
            "http://anotherurl",
                function(r) {
                    $("#feed").append(foo.some_property); 
                }
        );
}

答案 1 :(得分:0)

你不应该引用“r”传递给内部Json请求的数据吗?那应该包含不同的数据。否则,每次都会获得相同的外部响应数据“i”。