Skip to content Skip to sidebar Skip to footer

Get Json Data With Jquery

Hey guys I would like to know how can I get json data with ajax call. I tried this but seems won't work :P First I created a JavaScript file to put inside my json data elements : v

Solution 1:

Firstly, you have a syntax error in your example - there's too many closing braces on the $.ajax call, although I guess that's just a typo.

In your JSON, food is an array, so you need to use an indexer to get the properties of the objects within it:

success: function(data) {
    var result = data.food[0].name; // = "bread"alert(result);
});

Solution 2:

try this

$(document).ready(function() {
    $.ajax({
        async: false,
        dataType: "json",
        type:'GET',
        url:"food.js",
        success: function(data) {
            var result = data.food[0].name;
            alert(result);
        }
   });
});

Solution 3:

You need to loop through the returned data since it's an array:

$.each(data,function(i,val) {
    alert(data[i].name);
});

Solution 4:

I love how people are completely ignoring the fact that your "food.js" is not a JSON string, it's JavaScript code. This might work on old-school eval-based "JSON", but with jQuery AJAX your target file should be plain JSON. Remove the var food = from the start, and the ; from the end.

Then you can access data.food[0].name;

Solution 5:

In this case, you are trying to get an another javascript file via ajax. For do this, you can "include" your script ( of food.js ) in your page, using Ajax GetScript ( see here ).

Your code is mucth better when you request directly json files.

Post a Comment for "Get Json Data With Jquery"