Car*_*sta 0 javascript ajax jquery asynchronous
可能重复:
jQuery AJAX:成功时返回值
我试图通过查询获取JSON文件时,我有这个奇怪的参考问题:
var themeData;
$.getJSON("json/sample.js", function(data) {
themeData = data.theme;
console.log(themeData.sample[0].description);
});
console.log(themeData.sample[0].description);
Run Code Online (Sandbox Code Playgroud)
第一个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);
Run Code Online (Sandbox Code Playgroud)
如果你真的需要在"之后"调用一个方法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);
});
Run Code Online (Sandbox Code Playgroud)
编辑
您也可以使用async: falseJQuery ajax函数强制执行同步调用.
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback,
async: false
});
Run Code Online (Sandbox Code Playgroud)