Let’s create a new document in the Ajax folder to return our data in JSON format: AjaxJSONResponse.json.
{ "records": { "record": [ { "from": "John Doe", "to": "Everyone", "title": "Keep this record", "description": "This is the first of many XML records" }, { "from": "Gabriel J", "to": "Jhon Doe", "title": "Important message", "description": "Please read this message" }, { "from": "John Doe", "to": "Gabriel J", "title": "Re: Important message", "description": "Yes, I have read it!" } ] } }
If you look closely, you should see that this is a similar representation as the XML we had in our previous example, in fact, it’s the same information but in a different notation.
So let’s create a copy of our XMLAjaxDemo.html and create a new one called: JSONAjaxDemo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>AJAX Demo</title> <script> function loadAjaxReponseJSON() { var xmlHTTPRequest; var txtToBeWritten,record,i; if (window.XMLHttpRequest) {// Validation for Internet Explorer 7 and upo, Firefox, Chrome, etc xmlHTTPRequest=new XMLHttpRequest(); } else {// Web browser is Internet Explorer 5 or 6 xmlHTTPRequest=new ActiveXObject("Microsoft.XMLHTTP"); } xmlHTTPRequest.onreadystatechange=function() { if (xmlHTTPRequest.readyState==4 && xmlHTTPRequest.status==200) { var jsonResponse = JSON.parse(xmlHTTPRequest.responseText); txtToBeWritten=""; for (i=0;i<jsonResponse.records.record.length;i++) { txtToBeWritten = txtToBeWritten + jsonResponse.records.record[i].title + "<br>"; } document.getElementById("AjaxResponseJSONHere").innerHTML=txtToBeWritten; } } xmlHTTPRequest.open("GET","AjaxJSONResponse.json",true); xmlHTTPRequest.send(); } </script> </head> <body> <form id="form1"> <br/> <h1>AJAX DEMO: JSON<h1> <h2> Display record titles: <input type="button" id="submit" value="Click Me!" onclick="loadAjaxReponseJSON()"/> <div id="AjaxResponseJSONHere"> </div> </h2> </form> </body> </html>
Now let’s go over some of the differences:
- we use the responseText property instead the responseXML property. JSON is an object representation in a string.
- Instead of using DOM functions to access the content of the response, we can use json object as a regular object and access each property.
Let’s open the following web page: http://localhost:8080/Ajax/JSONAjaxDemo.html
Once we click on the Click Me! button, you will see the same result as our previous demo and the record’s title should be displayed.