Possible Duplicate:
jQuery AJAX: return value on success
当我尝试通过查询获取 JSON 文件时,遇到了这个奇怪的引用问题:
var themeData;
$.getJSON("json/sample.js", function(data) {
themeData = data.theme;
console.log(themeData.sample[0].description);
});
console.log(themeData.sample[0].description);
第一个 console.log 有效,第二个则无效。为什么会发生这种情况?
最佳答案
这是第二个没有被击中的(按代码中的时间顺序排列)。那是因为还没有设定。从服务器返回后,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);
});
编辑
您还可以使用 JQuery ajax 函数的 async: false
来强制同步调用。
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback,
async: false
});
关于调用时 Javascript 代码不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12701507/