这是第二个(按时间顺序在您的代码中)没有被击中。那是因为还没有设置。从服务器返回后,内部的回调getJSON
被异步调用。
var themeData;
// FIRST -- themeData currently null
$.getJSON("json/sample.js", function(data) {
// THIRD -- now themeData has a value, and gets logged
themeData = data.theme;
console.log(themeData.sample[0].description);
});
// SECOND -- themeData still null
console.log(themeData.sample[0].description);
如果您真的需要在“之后”调用方法getJSON
,那么请接受回调的想法。使用这样的东西。
var themeData;
function myCallback(data) {
console.log(data.sample[0].description);
}
$.getJSON("json/sample.js", function(data) {
themeData = data.theme;
console.log(themeData.sample[0].description);
myCallback(themeData);
});
编辑
您还可以强制同步调用,而不是使用async: false
JQuery ajax 函数。
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback,
async: false
});