更新时间:2023-01-16 15:33:58
如果您的真实代码是这样的结构,那么您在尝试访问尚未设置的数据时会遇到问题尚未.仅仅因为您的 $.getJSON()
高于 console.log()
并不意味着您在记录数据值之前得到响应.
If your real code is structured like that then you have a problem with trying to access the data that hasn't been set yet. Just because your $.getJSON()
is above console.log()
doesn't mean that you get the response before you log value of data.
因此,您的问题不在于范围,而在于时机:引入一些服务器端延迟,您的解决方案也可能崩溃.
So your problem is not scope, but rather the timing: introduce some server-side lag and your solution may as well crash.
如果收到回复,也许你应该设置一些标志:
Maybe you should set some flag if response was received:
var data, dataReceived = false;
$.getJSON("panorama.json",function(json){
data = json.images[0].src;
dataReceived = true;
console.log(data);
});
// somwhere later
if (dataReceived) {
console.log(data);
} else {
// you could use setTimeout() or setInterval here to re-check
console.log("data not received yet");
}