为了getAllSupportedItems
能够返回任何项目,AJAX 调用需要同步运行。
getJSON
转换为以下异步调用:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
异步是默认设置。因此,您需要将您的请求显式更改为同步请求:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback,
async: false
});
另一种方法是重新考虑您的使用方式getAllSupportedItems
并将其变成异步实用程序:
function getAllSupportedItems(callback){
$.getJSON("allItems.json",
function(data){
var allItems = [];
$.each(data.items,
function(item){
allItems.push(item);
});
callback(allItems);
// callback(data.items); should also work
});
}
更新
当我最初写这个答案时,jQuery 没有内置的 Deferred 支持。今天做这样的事情要简洁和灵活得多:
function getAllSupportedItems( ) {
return $.getJSON("allItems.json").then(function (data) {
return data.items;
});
}
// Usage:
getAllSupportedItems().done(function (items) {
// you have your items here
});