Javascript 变量范围:函数内的全局变量
我尝试将JSON数组分配给变量,如下所示:Javascript 变量范围:函数内的全局变量,javascript,json,Javascript,Json,我尝试将JSON数组分配给变量,如下所示: $.getJSON("tljson.json",function(result){ items = JSON.stringify(result); }); 然后在函数外部调用该变量: timeline.draw (items,options); 在getJSON函数内部使用alert(items)可以工作,但是在函数外部,它只返回“undefined”。我认为这是可行的,因为我在getJSON函数中将items声明为全局变量。我做错了什么?这是
$.getJSON("tljson.json",function(result){
items = JSON.stringify(result);
});
然后在函数外部调用该变量:
timeline.draw (items,options);
在getJSON函数内部使用alert(items)可以工作,但是在函数外部,它只返回“undefined”。我认为这是可行的,因为我在getJSON函数中将items声明为全局变量。我做错了什么?这是因为您的代码是在收到getJSON的响应之前执行的。像这样使用它:
function afterGetJSON(items) {
timeline.draw (items,options);
}
$.getJSON("tljson.json",function(result){
items = JSON.stringify(result);
afterGetJSON(items);
});
这是因为您的代码是在收到getJSON的响应之前执行的。像这样使用它:
function afterGetJSON(items) {
timeline.draw (items,options);
}
$.getJSON("tljson.json",function(result){
items = JSON.stringify(result);
afterGetJSON(items);
});
您可能没有等待
getJSON
函数完成。它是异步的,这意味着它下面的代码将在回调函数中的代码之前执行
alert(1);
$.getJSON("tljson.json",function(result){
alert(2);
items = JSON.stringify(result);
});
alert(3);
上面的例子实际上是先警告1
然后警告3
然后警告2
。请注意,3
在2
之前
为了修复代码,您需要等待回调函数被调用,以便在尝试使用该变量之前,回调函数可以为项
赋值。提出解决方案可能取决于您的情况,但一个简单的想法是从回调函数中调用一些函数
$.getJSON("tljson.json",function(result){
items = JSON.stringify(result);
doSomethingWithItems();
});
function doSomethingWithItems() {
alert(items); // Correctly alerts items.
}
您可能没有等待
getJSON
函数完成。它是异步的,这意味着它下面的代码将在回调函数中的代码之前执行
alert(1);
$.getJSON("tljson.json",function(result){
alert(2);
items = JSON.stringify(result);
});
alert(3);
上面的例子实际上是先警告1
然后警告3
然后警告2
。请注意,3
在2
之前
为了修复代码,您需要等待回调函数被调用,以便在尝试使用该变量之前,回调函数可以为项
赋值。提出解决方案可能取决于您的情况,但一个简单的想法是从回调函数中调用一些函数
$.getJSON("tljson.json",function(result){
items = JSON.stringify(result);
doSomethingWithItems();
});
function doSomethingWithItems() {
alert(items); // Correctly alerts items.
}