jQuery Ajax GET JSON - CodingTag
×


jQuery ajax-getJSON()

1015

  • This jQuery method is used to fetch the content of a server json file by using an AJAX HTTP GET request.

  • Related Topics:

    jQuery filter
    jQuery not

    jQuery ajax-getJSON

    Syntax:

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

    Parameter description:

  • url: This parameter represents the path of the server json file which data to be fetched by this method. It is mandatory.
  • data: This parameter represents the data to be send to server file. it is an optional parameter.
  • success(data,status,xhr): This parameter represents a user defined function which run after the success of the given method. It is also optional and has some additional parameters:

1 data: This parameter contains the data returned from the server.

2 Status: This parameter contains a string containing request status ("success", "notmodified", "error", "timeout", or "parsererror").

3 xhr: This parameter contains the XMLHttpRequest object.

Example:

In this example we display the content of a server JSON file into div element.

Step 1 Create a sample JSON file Json_data.json

json_data.json

{
"site" : "Coding Tag",
"url" : "https://www.codingtag.com",
"Current_topic" : "jQuery",
"Tutorial" : "getJSON() mehtod"
}

Step 2 Paste the below code into your file to fetch the content of above file.

<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
div{
background:pink;
font-weight: 700;
padding:5px;
margin:5px;
font-size:16px;
}
h3{
background:yellow;
padding:5px;
margin:5px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){

$.getJSON(
"json_data.json",
function(result){
$str= "<p>Website name is:" +result.site+
" <br>Website URL is:" +result.url+
"  <br>Current topic is:" +result.Current_topic+
"  <br>You are learing the tutorial :"
+result.Tutorial+
"</p>";
$("#res").html($str);
});

});
});
</script>
</head>
<body>
<h2> jQuery getJSON() Method Example </h2>
<div id="res">
Resultant JSON data will be show here....
</div>
<button> Click Me! </button>
</body>
</html>

Output:

When you click the button,



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments