调用时,Javascript代码不可用

时间:2012-10-03 03:32:36

标签: javascript jquery ajax asynchronous

  

可能重复:
  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工作,第二个不行。为什么会这样?

2 个答案:

答案 0 :(得分: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);
}); 

修改

您也可以使用JQuery ajax函数的async: false来强制执行同步调用。

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback,
  async: false
});

答案 1 :(得分:0)

不,$.getJSON是一种异步方法,当第二个console.log被调用时,那时没有themeData