04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 17: Ajax and JSON<br />

(continued)<br />

});<br />

}<br />

case “author”: return undefined;<br />

default: return value;<br />

alert(object.age); //30<br />

alert(object.author); //undefined<br />

In this code, the filter function increments every “ age ” value by one and removes any “ author ” key it<br />

comes across. All other values are returned directly. The resulting object has an age property equal to 30<br />

but no author property. This parsing functionality is used frequently with data returned from the server.<br />

Suppose that the file addressbook.php returns a JSON structure in the following format:<br />

[<br />

]<br />

{<br />

},<br />

{<br />

“name”: “Nicholas C. Zakas”,<br />

“email”: “nicholas@some-domain-name.com”<br />

“name”: “Jim Smith”,<br />

“email”: “jimsmith@some-domain-name.com”<br />

}, {<br />

“name”: “Michael Jones”,<br />

“email”: “mj@some-domain-name.com”<br />

}<br />

An Ajax request can be made to retrieve this data and populate a < ul/ > element on the client using the<br />

following code:<br />

var xhr = createXHR();<br />

xhr.onreadystatechange = function(){<br />

if (xhr.readyState == 4){<br />

if ((xhr.status > = 200 & & xhr.status < 300) || xhr.status == 304){<br />

var contacts = JSON.parse(xhr.responseText);<br />

var list = document.getElementById(“contacts”);<br />

for (var i=0, len=contacts.length; i < len; i++){<br />

var li = document.createElement(“li”);<br />

li.innerHTML = “ < a href=\”mailto:” + contacts[i].email + “\” > ” +<br />

contacts[i].name + “ < /a > ”;<br />

list.appendChild(li);<br />

}<br />

}<br />

}<br />

};<br />

xhr.open(“get”, “addressbook.php”, true);<br />

xhr.send(null);<br />

This code receives a JSON string from the server and parses it into a JavaScript array. From that point, it ’ s<br />

easy to iterate over each object in the structure to insert those values into the DOM. The < ul/ > element is<br />

filled with several < li/ > elements, each containing a link to send an e-mail message to a person.<br />

584

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!