Table of Contents
jQuery ajax getJson method is used to load json data from server using http get method. Lets go through syntax for getJson method.
Url:It is url for get request on server
data:Data which you want to send to server with request.
Success :Callback function which get executed when request succeeds.
Data which you send with get request will be in the form of query string.
1 2 3 |
jQuery.getJSON( url [, data ] [, success ] ) |
data:Data which you want to send to server with request.
Success :Callback function which get executed when request succeeds.
Data which you send with get request will be in the form of query string.
jQuery getJson example:
Lets first create the json file named country.json which we are going to read from server. country.json
1 2 3 4 5 6 |
{ "countryName" : "India", "population" : 10000 } |
Lets create html file named jQueryGetJson.html.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<meta content="text/html;charset=utf-8" http-equiv="Content-Type"> <meta content="utf-8" http-equiv="encoding"> <title>getJson example</title> <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script> <script type="text/javascript" language="javascript"> $(document).ready(function() { $("button").click(function(event){ $.getJSON("country.json", function(country) { $("#getJsonDiv").html('<p> Name: ' + country.countryName + ''); $("#getJsonDiv").append('<p>Population : ' + country.population+ ''); }); }); }); </script> <div id="getJsonDiv"> jQuery ajax getJSON example </div> <button>Get country data</button> |
Lets deploy html file on server and send getJson request.
When you click on Get country data , you will get below output
Explanation:
- $(document).ready(function() : This function will get called when fully DOM is loaded.
- $(“button”).click(function(event) : This function will get called when “get country data” button is clicked.
- Â $.getJSON(“country.json”, function(country) : Here we are calling getJson method and URL is “country.json”. Â When request is successfully completed, callback function will be get called.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.