The jQuery getJSON Method (.getJSON()) is an AJAX method that is used to fetch JSON data using HTTP GET request.
$(selector).getJSON(url,data,success(data,status,xhr))
Parameter | Description |
---|---|
url | Required. The URL to send the request to. |
data | Optional. The data to be sent to the server |
success(result,status,xhr) | Optional. The callback function to run when the request is successful.
|
$.getJSON({
url: "file.json"
}).done(function (result, status, xhr) {
alert(result)
}).fail(function (xhr, status, error) {
alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
});
The .done() will be called when the AJAX request completes while .fail() will be called when the AJAX request fails.
I have a json file named product.json.
[
{
"Product": "Mini Skirt size 38",
"color": "Brown",
"Price": "$40.77"
},
{
"Product": "Women Pant size 39",
"color": "Black",
"Price": "$21.45"
},
{
"Product": "Men Coat size 47",
"color": "Pink",
"Price": "$101.50"
}
]
Now with .getJSON() method I will show the file’s content in HTML format and inside a div element.
<div id="jsonData"></div>
$.getJSON({
url: "product.json",
success: function (result, status, xhr) {
var table = $("<table><tr><th>Product</th><th>Color</th><th>Price</th></tr>");
var tr;
for (var i = 0; i < result.length; i++) {
tr = $("<tr>");
tr.append("<td>" + result[i].Product + "</td>");
tr.append("<td>" + result[i].color + "</td>");
tr.append("<td>" + result[i].Price + "</td>");
tr.append("</tr>");
table.append(tr);
}
table.append("</table>");
$("#jsonData").html(table);
}
});
Here I will show how to fetch images from flickr API.
<div id="flickrData"></div>
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON(flickerAPI, {
tags: "nicole kidman",
tagmode: "any",
format: "json"
}).done(function (result, status, xhr) {
$.each(result.items, function (i, item) {
$("<img>").attr("src", item.media.m).appendTo("#flickrData");
if (i === 5) {
return false;
}
});
}).fail(function (xhr, status, error) {
alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
});
I have passed the optional data parameters (tags, tagmode, format) to the jQuery getJSON method.
.
You can also download the full source codes: