使用Jquery从本地文件中获取JSON对象 [英] Using Jquery to get JSON objects from local file

查看:127
本文介绍了使用Jquery从本地文件中获取JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Jquery从本地文件中获取JSON对象(产品)列表,并将所有对象存储在名为allItems的单个数组中。该文件与代码位于同一目录中,并称为allItems.json。以下是我现在的做法:

I'm trying to get a list of JSON objects (products) from a local file using Jquery and store all the objects in a single array called allItems. The file is co-located in the same directory as the code, and it's called "allItems.json". Here's how I'm doing it now:

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调用需要同步运行。

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 并将其变为异步实用程序:

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
});

这篇关于使用Jquery从本地文件中获取JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆