我在
中设置变量$.getJSON("filename.json", function(data){ ... });
方法,并在调用此函数后立即打印变量。然后控制台告诉我我的变量不存在。为什么会发生这种情况,我该如何解决?
错误代码:
function
$.getJSON("dimple1.json", function(data){
var data1 = data;
console.log(data1);
});
console.log(data1); //gives: "ReferenceError: data1 is not defined"
}
控制台输出:
[14:40:46.044] Unknown property 'box-sizing'. Declaration dropped.
[14:40:46.049] ReferenceError: data1 is not defined
[14:40:46.103] not well-formed
[14:40:46.104] ({information:[{month:"January", 'Unit Sales':"18000"}, {month:"February", 'Unit Sales':"6000"}, {month:"March", 'Unit Sales':"20000"}, {month:"April", 'Unit Sales':"35000"}, {month:"May", 'Unit Sales':"13000"}, {month:"June", 'Unit Sales':"4000"}, {month:"July", 'Unit Sales':"6000"}, {month:"August", 'Unit Sales':"9500"}, {month:"September", 'Unit Sales':"28000"}, {month:"October", 'Unit Sales':"21000"}, {month:"November", 'Unit Sales':"10000"}, {month:"December", 'Unit Sales':"6000"}]})
答案 0 :(得分:0)
这是因为data1
正在getJSON调用的'closure'中定义。就脚本的其余部分而言,它不存在。
如果您在getJSON调用之外定义了变量,请执行以下操作:
var data1
function
$.getJSON("dimple1.json", function(data){
data1 = data;
console.log(data1);
});
console.log(data1); //gives: "ReferenceError: data1 is not defined"
}
你可以引用变量,但是值仍然是空的 - 因为日志发生在设置值之前。