AJAX JSON Example
AJAX can be used to interact with JSON files.
AJAX JSON Example
The following example will demonstrate how a web page can use AJAX to read information from a JSON file:
Example
Example Explanation - loadXMLDoc() Function
When the user clicks the "Get Course Data" button, the loadXMLDoc() function is executed.
The loadXMLDoc() function creates an XMLHttpRequest object, adds a function to execute when the server response is ready, and sends the request to the server.
When the server response is ready, we use the JSON.parse() method to convert the data into a JavaScript object.
Asynchronous Loading of JSON Document
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// IE7+, Firefox, Chrome, Opera, Safari code
xmlhttp=new XMLHttpRequest();
}
else
{
// IE6, IE5 code
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var myArr = JSON.parse(this.responseText);
myFunction(myArr)
}
}
xmlhttp.open("GET","/try/ajax/json_ajax.json",true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send();
}
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].title + '</a><br>';
}
document.getElementById("myDiv").innerHTML=out;
}
AJAX Server Page
The server page used in this example is actually a JSON file named "json_ajax.json".
The JSON data is as follows:
json_ajax.json File:
[
{
"title": "JavaScript Tutorial",
"url": "https://www.tutorialpro.org/js/"
},
{
"title": "HTML Tutorial",
"url": "https://www.tutorialpro.org/html/"
},
{
"title": "CSS Tutorial",
"url": "https://www.tutorialpro.org/css/"
}
]
Sending JSON Data:
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "tutorialpro" } }));