Skip to content Skip to sidebar Skip to footer

Using Jquery To Get Json Objects From Local File

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

Solution 1:

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:

functiongetAllSupportedItems(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:

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

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

Solution 2:

How are you using this? If you're expecting the main function ("getAllSupportedItems") to return the array you make, well that won't work. The $.getJSON function is asynchronous, and so the handler won't actually build the array until after the outer function has returned.

Post a Comment for "Using Jquery To Get Json Objects From Local File"