JSON stands for JavaScript Object Notation which is lightweight data interchange format used to exchange text information. The jQuery getJSON() method access the data of JSON from the remote location by using GET HTTP request and also used to transfer and storing the data independently. It contains the URL to which request is sent to the server with request and callback function is executed if the request succeeds.
JQuery getJSON Syntax
$.getJSON(url, [data], [callback])
Following are parameters used by getJSON() method:
- url: It is used to send request to the specific URL.
- data: The requested data that has to be sent to the server.
- callback: It is a optional callback function, executed when the data is loaded successfully.
JQuery getJSON Example
First create a JSON file, save it as result.json and add some contents which are to be load on the web page.
{ "name": "RushaliB", "seat" : "125634", "perc": "69%" }
After creating a JSON file, write the coding part for the processing of the ajaxgetJSON() method and save it with .html extension. Following script defines html file.
<!DOCTYPE html> <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> <meta content="utf-8" http-equiv="encoding"> <head> <title>the title</title> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script type="text/javascript" language="javascript"> $(document).ready(function() { $("button").click(function(event){ $.getJSON("result.json", function(jd) { $("div").html('<p> Name: ' + jd.name + '</p>'); $("div").append('<p>Seat No : ' + jd.seat+ '</p>'); $("div").append('<p>Percentage: ' + jd.perc+ '</p>'); }); }); }); </script> </head> <body> <div> jQuery ajax getJSON method example </div> <button>CLICK</button> </body> </html>
- The above program highlights how to access the data of JSON file on the server by clicking the button on the server.
- $(“button”).click(function(event){ }); line defines click event which occurs when button is clicked.
- $.getJSON(“result.json”, function(jd) {}); line indicates getJSON() method to access data of JSON file. The contents of the “result.json” file will get display on the browser.
- $(“div”).html(‘Name: ‘ + jd.name +); line indicates the html method.
- $(“div”).append(‘Percentage: ‘ + jd.perc+); line adds the percentage value.
JQuery getJSON Demo
When you run the above example, you would get the following output :