To retrieve data from JSON file using jQuery and Ajax, The jQuery.getJSON( url, [data], [callback]) method loads JSON data from the server using a GET HTTP request.
Here is the description of all the parameters used by this method:
Let’s say we have the following JSON content in employee.json file
{
"name": "Rahul",
"age": "30",
"sex": "male"
}
The following is the code snippet showing the usage of this method:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Adding two number in jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#employeeid").click(function (event) {
$.getJSON('employee.json', function (response) {
$('#stage').html('<p> Name: ' + response.name + '</p>');
$('#stage').append('<p>Age : ' + response.age + '</p>');
$('#stage').append('<p> Sex: ' + response.sex + '</p>');
});
});
});
</script>
</head>
<body>
<input type="button" id="employeeid" value="Load Employee Data" />
<br />
<div id="stage" style="background:green; color:white">
</div>
</body>
</html>
Output
Now click to load json data.