AJAX with JSON - The XMLHTTP Request to retrieve JSON
(Page 3 of 4 )
The boiler plate portion of AJAX which consists of making the XMLHttpRequest is exactly the same as shown in the partially colored portion of the next listing. However the AJAX call is now made to get a JSONText file, JSONWebStudents.txt described earlier from the web server (localhost).
Listing of AjaxNewJson.htm:
<HTML>
<HEAD>
<TITLE>AJAX with JSON</TITLE>
<SCRIPT LANGUAGE=javascript>
<!--
var xhr = false;
function getPage (url) {
xhr = false;
//this is the Microsoft browser compatible instantiation
//of XmlHttpRequest
xhr = new ActiveXObject("Msxml2.XMLHTTP");
if (!xhr) {
alert ('XMLHttp failed to instantiate');
return false;
}
xhr.onreadystatechange = statusCheck;
xhr.open ('GET', url, true);
xhr.send (null);
}
function statusCheck() {
if (xhr.readyState == 4) { if (xhr.status == 200) {
//document.write(xhr.responseText);
alert("Status OK");
var jsonT = eval('('+ xhr.responseText +')');
document.write ("jsonT.wclass.length= " + jsonT.wclass.length);
document.write("<br/>");
document.write("jsonT.wclass[0].name"+ jsonT.wclass[0].name);
} }
}
</script>
</head>
<BODY>
<INPUT type="button" id=button2
onclick="getPage ('http://localhost/JSONWebStudents.txt')"
value="Get JSON" />
</BODY>
</HTML>
The response from the server xhr with its responseText property is evaluated using the JavaScript eval() function which evaluates whatever is given as its argument. It converts the JSON Text to a JSON object (jsonT). With the object in the hand it is easy to recover the values using the dot notation as shown in the two document.write() statements that follow the eval(). The resulting display when the above file is browsed is shown in the next picture. It will be helpful to read the earlier tutorial JSON Basics.

Next: Output formatting >>
More JavaScript Articles
More By Jayaram Krishnaswamy