HTML and CSS Reference
In-Depth Information
Create the Ajax Program. The Ajax program will make a request to the server to
get text in the . json file. The server will return the text in the requestResponseText prop-
erty of the Ajax request object. Next Ajax must convert the JSON text into a JavaScript
object (or array). To accomplish this, we can use the JavaScript built-in eval() function,
as long as security is not an issue. For our demo it is not, because Ajax communication
is permitted within this domain where the page originated, and therefore, trusted. (Later
we will download the JSON library, json2 , to accomplish the same task.)
The eval() function evaluates the text and creates a JavaScript data structure, consist-
ing of key/value pairs, either an array or object.
var myObject = eval('(' + myJSONtext + ')');
Now with the dot notation, we can get the values associated with the keys; for exam-
name = // object notation
color = myObject[0] // array notation
After the data has been parsed and stored in variable, it is ready to be displayed in the
Steps for Using Ajax and a JSON Array
1. The JSON text file, " colors.json " contains the following array:
[ "red", "blue", "green", "yellow" ]
2. The Ajax program requests the file and evals the response.
// Segment from the Ajax program
function getXMLContents(httpRequest) {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
var colors = eval('('+httpRequest.responseText +')') ;
alert(colors) ;
// alert( " I like " + colors[3] ) Prints " yellow "
else {
alert('There was a problem with the request.');
Search WWH ::

Custom Search