且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-03 11:27:16

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

For getAllSupportedItems to be able to return any items, the AJAX call needs to run synchronously.

getJSON 转换为以下异步调用:

getJSON translates to the following asynchronous call:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

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

Asynchronous is the default. You therefore need to explicitly change your request to a synchronous one:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback,
  async: false
});

另一种方法是重新考虑使用 getAllSupportedItems $ c $的方式c>并将其变为异步实用程序:

An alternative is to rethink the way you use getAllSupportedItems and make it into an asynchronous utility:

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支持。今天做这样的事情更加简洁灵活:


Update

When I initially wrote this answer, jQuery didn't have built-in Deferred support. It is a lot more concise and flexible to do something like this today:

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

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