0

可能重复:
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);

第一个 console.log 有效,第二个无效。为什么会这样?

4

2 回答 2

5

这是第二个(按时间顺序在您的代码中)没有被击中。那是因为还没有设置。从服务器返回后,内部的回调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: falseJQuery ajax 函数。

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback,
  async: false
});
于 2012-10-03T03:34:52.243 回答
0

No, $.getJSON is a async method, when the second console.log is called, there's no themeData at that time.

于 2012-10-03T03:35:45.003 回答