Quick Reach
jQuery getJSON() method
As explained in the previous chapter, the jQuery get() method is used to load data using HTTP get request method. The getJSON() method of jQuery is specifically used to load JSON data by using the HTTP GET request.
The JSON, acronym for JavaScript Object Notation, is a lightweight data-interchange format, used to store and exchange text information.
A running example of jQuery getJSON
See example online with data loaded from getJSON.json file
How to use the getJSON method?
This is how you may use the getJSON method:
$.getJSON( url, [data], success_function( data, Status, xhr ))
Where:
URL: is a string specifying the server to which request is sent. This is required parameter.
data: Data to be sent to the server along with HTTP request
success: Optional parameter. If a request is successful this function will execute if given. It also contains returned data from the server. The other parameters in this call function are:
success_function(data, status, xhr)
Where:
- Data = returned data from server
- Status = returns request status i.e. success, error, timeout, notmodified
- xhr= it contains XMLHttpRequest object.
A live demo of getJSON jQuery
The example below shows how to load text data from JSON file, namely getjson.json. Place this file at the same location where you are calling getJSON() method. The data loaded after clicking the button is shown in paragraphs.
Experience this example online
First getjson.json file:
1
2
3
4
5
6
7
8
9
|
{
“SiteName”: “Tutorials Collection”,
“Tutorial”: “JQuery Tutorial”,
“Lesson”: “getJSON() Method”
}
|
HTML file code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<html>
<head>
<script src=“http://code.jquery.com/jquery-1.10.1.min.js”>
</script>
<script>
$(document).ready(function(){
$(“#btnjson”).click(function(){
$.getJSON(“getjson.json”,function(ajaxresult){
$(“#SiteName”).append(ajaxresult.SiteName);
$(“#Tutorial_Name”).append(ajaxresult.Tutorial);
$(“#Lesson”).append(ajaxresult.Lesson);
});
});
});
</script>
</head>
<body>
<button id=“btnjson”>Load JSON data from getjson.json file!</button>
<p id=“SiteName”>Site Name: </p>
<p id=“Tutorial_Name”>Tutorial Name: </p>
<p id=“Lesson”>Lesson: </p>
</body>
</html>
|
Experience this example online
Useful reading: jQuery Get() method | jQuery post method
Leave A Comment?