04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 17: Ajax and JSON<br />

alert(xhr.responseText);<br />

} else {<br />

alert(“Request was unsuccessful: “ + xhr.status);<br />

}<br />

}<br />

};<br />

xhr.open(“get”, “http://www.somewhere-else.com/page/”, true);<br />

xhr.send(null);<br />

Unlike the XDR object in IE, the cross - domain XHR object allows access to the status and statusText<br />

properties as well as allowing synchronous requests. There are some additional limitations on a cross -<br />

domain XHR object that are necessary for security purposes. They are as follows:<br />

❑<br />

❑<br />

❑<br />

Custom headers cannot be set using setRequestHeader() .<br />

Cookies are neither sent nor received.<br />

The getAllResponseHeaders() method always returns an empty string.<br />

Since the same interface is used for both same - and cross - domain requests, it ’ s best to always use a<br />

relative URL when accessing a local resource, and an absolute URL when accessing a remote resource.<br />

This disambiguates the use case and can prevent problems such as limiting access to header and/or<br />

cookie information for local resources.<br />

Like the IE approach to cross - domain requests, the Firefox implementation hasn ’ t been around long<br />

enough to establish best practices around it.<br />

JSON<br />

Even though XML was a large part of the Ajax movement, it was quickly met with disdain from<br />

JavaScript developers. As discussed in Chapter 15 , XML manipulation in JavaScript is quite different<br />

from browser to browser, and extracting data from an XML structure requires walking a DOM<br />

document, which takes a fair amount of code. Douglas Crockford introduced a data format called<br />

JavaScript Object Notation (JSON) to try to ease some of the data - access concerns of XML.<br />

JSON is based on a subset of the JavaScript syntax, most notably object and array literals. Using these<br />

constructs, it ’ s possible to create a structured data format capable of representing the same types of data<br />

as XML. For example, a collection of name - value pairs can be represented as an object containing named<br />

properties as shown here:<br />

{<br />

}<br />

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

“title”: “Software Engineer”,<br />

“author”: true,<br />

“age”: 29<br />

581

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

Saved successfully!

Ooh no, something went wrong!