这是一个异步调用,所以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;
};