2015-05-19 152 views
-1

我在我想读取的文件中有json数据。它将打印到console.log中正确的文件数据。从AJAX请求返回数据

如何将这些数据存入变量x?当我运行代码时,x是未定义的。

function getData() { 
     $.get('data/APPFeaturesMetaData.json', function (data) { 
      console.log(data); 
      return data; 
     }); 
    }; 

    var x = getData(); 

回答

3

这是一个异步调用,所以var x = getData();在AJAX请求完成之前运行。

答案是,使用推迟它看起来是这样的:

var request = $.ajax(
{ 
    url: url, 
}); 

// When the request is done, do something with data. 
request.done(function (data) { 
    console.log(data); 
}); 

在你的情况,这是不同的,如果你想返回的数据,你将有一些作用域的问题。这个修复非常简单,下面是你的最终代码的样子,我会在评论中解释一些东西:

function getData() { 

    // This is where we store the data. 
    var myData; 

    // This will refference current object. 
    // You need to keep the refference of this object. 
    var self = this; 

    $.get('data/APPFeaturesMetaData.json').done(function(data) { 
     // the keyword `this` will not work here, because you're inside an AJAX callback. 
     // When you say `this`, you're actually refferencing the AJAX object 
     // And not the getData object. 
     self.myData = data; 
    }); 

    return myData; 
};