AJAX JSON Example


AJAX can be used for interactive communication with JSON files.


AJAX JSON Example

The following example will demonstrate how a web page uses AJAX to read information from a JSON file:

Example




Try it Yourself »


Example Analysis - loadXMLDoc() Function

When the user clicks the above"Get Course Data"button, the loadXMLDoc() function will be executed.

The loadXMLDoc() function creates an XMLHttpRequest object, adds a function to be executed when the server response is ready, and sends the request to the server.

When the server response is ready, we use theJSON.parse()method to convert the data into a JavaScript object.:

Asynchronously Load JSON Document

function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) { //IE7+, Firefox, Chrome, Opera, Safari browsers execute the code xmlhttp=new XMLHttpRequest(); } else { //IE6, IE5 browsers execute the 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 the above example is actually a file named "json_ajax.json" JSON file.

The JSON data is as follows:

json_ajax.json file:

[ { "title": "JavaScript Tutorial", "url": "https://www.example.com/js/" }, { "title": "HTML Tutorial", "url": "https://www.example.com/html/" }, { "title": "CSS Tutorial", "url": "https://www.example.com/css/" } ]

Send JSON data:

xmlhttp.send(JSON.stringify({ "email": "admin@example.com", "response": { "name": "example" } }));
Other extensions