Javascript jQuery getJson()在循环中不更改值的行为非常奇怪
好的,这个问题很奇怪。我正在使用getJSON()接收项目列表。对于每个返回的项,我再次使用getJSON()执行查找。在返回第二次查找时,我尝试将for循环范围中的变量附加到DOM,但输出是相同的。奇怪的是,当我在第二个getJSON()之前发出变量的alert()时,变量会像应该的那样发生变化 这是虫子吗?看起来getJSON正在缓存一些东西Javascript jQuery getJson()在循环中不更改值的行为非常奇怪,javascript,jquery,Javascript,Jquery,好的,这个问题很奇怪。我正在使用getJSON()接收项目列表。对于每个返回的项,我再次使用getJSON()执行查找。在返回第二次查找时,我尝试将for循环范围中的变量附加到DOM,但输出是相同的。奇怪的是,当我在第二个getJSON()之前发出变量的alert()时,变量会像应该的那样发生变化 这是虫子吗?看起来getJSON正在缓存一些东西 $.getJSON( "http://someurl", function(data) { var items = data
$.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!!
}
)
}
}
)
$.getJSON(
"http://someurl",
功能(数据){
var items=data.items;
对于(i=0;iAjax是异步的
在内部getJSON发出的第一个HTTP请求返回之前,您可能会设法通过外部循环进行循环,因此i
是第一次运行内部回调之前的最后一个值
添加警报时,循环执行将暂停,直到单击“确定”按钮,这将为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);
}
);
}
for(var i=0;iAjax是异步的
在内部getJSON发出的第一个HTTP请求返回之前,您可能会设法通过外部循环进行循环,因此i
是第一次运行内部回调之前的最后一个值
添加警报时,循环执行将暂停,直到单击“确定”按钮,这将为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);
}
);
}
for(var i=0;i您不应该引用“r”传递到内部Json请求的数据吗?它应该包含不同的数据。否则,您每次都会得到相同的外部响应数据“i”。您不应该引用“r”吗传递给内部Json请求?的数据应包含不同的数据。否则,您将获得相同的外部响应数据“i”每次。我都有一种感觉。你的回答证实了这一点。事实上,当我使用console.log时,输出是不同的。所以,thx代表“var”关键字提醒。我已经使用python一段时间了,刚刚回到JS开发了一个小应用程序。我有一种感觉。你的回答证实了这一点。事实上,当我使用c在sole.log上,输出是differentialso,thx表示“var”关键字提醒。我使用python已经有一段时间了,刚刚回到JS开发了一个小应用程序。我从第二个getJSON()中提取了一些代码,以简化这里的代码,使其看起来没有被使用。我从第二个getJSON()中提取了一些代码简化此处的代码,使其看起来不被使用。