Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
108
rated 0 times [  110] [ 2]  / answers: 1 / hits: 41102  / 14 Years ago, sat, may 8, 2010, 12:00:00

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


Based on this example: http://api.jquery.com/jQuery.getJSON/


More From » jquery

 Answers
20

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


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

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



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

[#96845] Wednesday, May 5, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zahrafrancisr

Total Points: 176
Total Questions: 105
Total Answers: 99

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
;