我正在尝试使用jQuery从本地文件中获取JSON对象(产品)列表,并将所有对象存储在称为Allitems的单个数组中。该文件以与代码相同的目录共同分配,称为“ Allitems.json”。这是我现在这样做的方式:

function getAllSupportedItems(){
    var allItems = new Array();
    $.getJSON("allItems.json",
         function(data){
             $.each(data.items, 
             function(item){
                 allItems.push(item);
             });
         });
    return allItems;
}

基于此示例: http://api.jquery.com/jquery.getjson/

有帮助吗?

解决方案

为了 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没有内置的递延支持。今天做这样的事情更加简洁和灵活:

function getAllSupportedItems( ) {
    return $.getJSON("allItems.json").then(function (data) {
        return data.items;
    });
}

// Usage:
getAllSupportedItems().done(function (items) {
    // you have your items here
});

其他提示

您如何使用这个?如果您期望主函数(“ getallSupportedItems”) 返回 您制作的阵列,那是行不通的。这 $.getJSON 功能是 异步, ,因此,直到外部功能返回后,处理程序实际上才能构建数组。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top