使用Jquery从本地文件中获取JSON对象

Tho*_*yme 12 javascript jquery json local-files

我正在尝试使用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;
}
Run Code Online (Sandbox Code Playgroud)

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

Ate*_*ral 23

为了getAllSupportedItems能够返回任何项目,AJAX调用需要同步运行.

getJSON 转换为以下异步调用:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});
Run Code Online (Sandbox Code Playgroud)

异步是默认值.因此,您需要明确地将您的请求更改为同步请求:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback,
  async: false
});
Run Code Online (Sandbox Code Playgroud)

另一种方法是重新考虑您使用的方式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
         });
}
Run Code Online (Sandbox Code Playgroud)

更新

当我最初写这个答案时,jQuery没有内置的Deferred支持.今天做这样的事情更加简洁灵活:

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

// Usage:
getAllSupportedItems().done(function (items) {
    // you have your items here
});
Run Code Online (Sandbox Code Playgroud)