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/
For
getAllSupportedItemsto be able to return any items, the AJAX call needs to run synchronously.getJSONtranslates to the following asynchronous call:Asynchronous is the default. You therefore need to explicitly change your request to a synchronous one:
An alternative is to rethink the way you use
getAllSupportedItemsand make it into an asynchronous utility: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: