jQuery | getJSON() Method

The getJSON() method in jQuery fetches JSON-encoded data from the server using a GET HTTP request.

Syntax:

$(selector).getJSON(url,data,success(data,status,xhr))

Parameters: This method accepts three parameters as mentioned above and described below:



  • url: It is required parameter. It is used to specify the URL in the form of a string to which the request is sent
  • data: It is an optional parameter which specifies data that will be sent to the server.
  • callback: It is also an optional parameter which runs when the request succeeds .

Return Value: It returns XMLHttpRequest object.

Below example illustrates the getJSON() method in jQuery:

employee.json file:

{
“name”: “Tony Stark”,
“age” : “53”,
“role”: “Techincal content writer”,
“company”:”Geeks for Geeks”
}

Example: This example get the JSON file and display its content.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        jQuery getJSON() Method
    </title>
      
    <script src=
    </script>
      
    <!-- Script to get JSON file and display its content -->
    <script type = "text/javascript" language="javascript">
        $(document).ready(function() {
               
            $("#fetch").click(function(event){
                $.getJSON('employee.json', function(emp) {
                    $('#display').html('<p> Name: ' + emp.name + '</p>');
                    $('#display').append('<p>Age : ' + emp.age+ '</p>');
                    $('#display').append('<p> Role: ' + emp.role+ '</p>');
                    $('#display').append('<p> Company: ' + emp.company+ '</p>');
                });
            });
        });
      </script>
   </head>
       
   <body>
      <p>
          Click on the button to fetch employee data
      </p>
           
      <div id = "display" style = "background-color:#39B54A;"></div>
           
      <input type = "button" id = "fetch" value = "Fetch Employee Data" />
        
   </body>
</html>

chevron_right


Output:
Before Clicking the button:
before clicking the button
After Clicking the button:
After Clicking the button



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.