jQuery.getJSON()
S2C Home « Ajax « jQuery.getJSON()
Asynchronous HTTP (Ajax) JSON encoded load request.
Description
The jQuery.getJSON()
Ajax method, allows us to load data from the server, that has been JSON encoded, using a HTTP GET request.
Shorthand version $.getJSON()
- Browsers operate the 'same origin policy', which means a request can not successfully retrieve data from a different domain, subdomain, or protocol. jQuery 'Ajax' requests are subject to this security restriction,
the exceptions being requests made with a
datatype
of 'script' or 'jsonp'. - The
jQuery.getJSON()
method returns ajqXHR
object which is a superset of the browser's nativeXMLHttpRequest
object. ThejqXHR
object implements thePromise
interface, giving it all the properties, methods, and behavior of a Promise. See the lesson on theDeferred
object for details of this. For standardization with theDeferred
object, thejqXHR
object also provides.always()
,.done()
and.fail()
methods. These methods take a function argument that is called when thejQuery.getJSON()
request terminates and the function receives the same arguments as the same-named.complete()
.success()
and.error()
setting callbacks respectively. This allows assignment of multiple callbacks for a single request as well as assigning callbacks after the request has completed. For completed requests, the callback is fired immediately.- It should be noted that
.complete()
.success()
and.error()
callbacks are deprecated from use on request completion from jQuery 1.8. This is for completion processing only and the Ajax settings will still have these values. Best practice is to use.always()
,.done()
and.fail()
methods on request completion to future proof code.
- It should be noted that
- A
jqXHR
object will expose the following properties and methods for backward compatibility with theXMLHttpRequest
object:
jqXHR Object | Description |
---|---|
Methods | |
abort() | Cancels the currently executing request. |
getAllResponseHeaders() | Returns a string containing the names and value of all response headers. |
getResponseHeader(name) | Returns the value of the specified response headers. |
.overrideMimeType() | Used in the beforeSend() callback function, to modify the response content-type header. |
setRequestHeader(name, value) | Set a request header using the specified name and value. |
Properties | |
readyState | An integer indicating the current state of the request. |
responseText | Underlying request responded with text. |
responseXML | Underlying request responded with xml. |
status | Response status code returned from the server. |
statusText | Status text message returned by the response. |
Syntax
Signature | Description |
---|---|
jQuery.getJSON( url [, data] | Load data from the server, that has been JSON encoded, using a HTTP GET request. |
Parameters
Parameter | Description | Type |
---|---|---|
url | A string containing the URL to send the request to. | String |
data | A map or string sent to the server with the request.
|
PlainObject |
function(data, textStatus, jqXHR) | A callback function executed when the request succeeds. | Function |
Return
A jqXHR
object.
jQuery.getJSON( url [, data]
[, function(data, textStatus, jqXHR)] )
ExamplesTop
[, function(data, textStatus, jqXHR)] )
Load data from the server, that has been JSON encoded, using a HTTP GET request.
This is a shorthand Ajax function, which is equivalent to using the jQuery.ajax()
method as follows:
$.ajax({
url: url
,
dataType: 'json',
data: data
,
success: callback
});
In the example below when we press the button the first time we use the jQuery.getJSON()
method with a url and a success handler. We interrogate the returned JSON data and move it to an array before appending it to our page.
$(function(){
$('#btn5').one('click', function(){
$.getJSON('../pages/testfileb.html', function(data) {
var sayingsList = [];
$.each(data, function(key, val) {
sayingsList.push('<li>' + val + '</li>');
});
$('<ul/>', {html: sayingsList.join('')}).appendTo('#div4');
}).done(function() { $('#div4').append('getJSON request succeeded! </li>'); })
.fail(function() { $('#div4').append('getJSON request failed! </li>'); })
.always(function() { $('#div4').append('getJSON request ended! </li></li>');
});
});
});
/*
* The external JSON file called from $.getJSON() (url: "../pages/testfileb.html")
* is shown below.
*/
{
"1": "A stitch in time saves nine",
"2": "The quick brown fox jumps over the lazy dog",
"3": "10 green bottles",
"4": "Blood is thicker than water",
"5": "A bird in the hand is worth two in the bush",
"6": "Prevention is better than cure",
"7": "To be or not to be"
}
div4. Some initial text.
Related Tutorials
jQuery Advanced Tutorials - Lesson 9 - Ajax Shorthand Methods