Utilizzando jQuery per ottenere oggetti JSON da file locale
-
04-10-2019 - |
Domanda
Sto cercando di ottenere un elenco di oggetti JSON (prodotti) da un file locale utilizzando jQuery e memorizzare tutti gli oggetti in un singolo array chiamato AllItems. Il file è co-trova nella stessa directory del codice, e si chiama "allItems.json". Ecco come lo sto facendo ora:
function getAllSupportedItems(){
var allItems = new Array();
$.getJSON("allItems.json",
function(data){
$.each(data.items,
function(item){
allItems.push(item);
});
});
return allItems;
}
In base a questo esempio: http://api.jquery.com/jQuery.getJSON/
Soluzione
Per getAllSupportedItems
per essere in grado di restituire tutti gli articoli, le esigenze di chiamata AJAX per eseguire in modo sincrono.
getJSON
traduce al seguente chiamata asincrona:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
asincrono è l'impostazione predefinita. È pertanto necessario modificare in modo esplicito la richiesta a uno sincrono:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback,
async: false
});
Un'alternativa è quella di ripensare il modo di usare getAllSupportedItems
e farne un programma di utilità asincrono:
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
});
}
Aggiorna
Quando inizialmente ho scritto questa risposta, jQuery non ha avuto il supporto incorporato differita. E 'molto più conciso e flessibile per fare qualcosa del genere oggi:
function getAllSupportedItems( ) {
return $.getJSON("allItems.json").then(function (data) {
return data.items;
});
}
// Usage:
getAllSupportedItems().done(function (items) {
// you have your items here
});
Altri suggerimenti
Come stai usando questo? Se vi aspettate la funzione principale ( "getAllSupportedItems") per ritorno l'array si fanno, bene che non funziona. La funzione $.getJSON
è asincrono , e quindi il gestore non sarà effettivamente costruire la matrice fino a dopo la funzione esterna è tornato.