gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 02:00:00 24 4
gpt4 key购买 nike

我正在尝试使用 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 没有内置的 Deferred 支持。今天做这样的事情要简洁和灵活得多:

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

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

关于javascript - 使用 Jquery 从本地文件中获取 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2792423/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com