25.02.2013 Views

Peter Lubbers - Pro HTML 5 Programming

Pro HTML 5 Programming

Pro HTML 5 Programming

SHOW MORE
SHOW LESS

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

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

130<br />

CHAPTER 5 ■ USING THE COMMUNICATION APIS<br />

Listing 5-7. Checking if cross-origin support is available in XMLHttpRequest<br />

var xhr = new XMLHttpRequest()<br />

if (typeof xhr.withCredentials === undefined) {<br />

document.getElementById("support").inner<strong>HTML</strong> =<br />

"Your browser does not support cross-origin XMLHttpRequest";<br />

} else {<br />

document.getElementById("support").inner<strong>HTML</strong> =<br />

"Your browser doessupport cross-origin XMLHttpRequest";<br />

}<br />

Making Cross-Origin Requests<br />

To make a cross-origin XMLHttpRequest, you must first create a new XMLHttpRequest object, as shown<br />

in the following example.<br />

var crossOriginRequest = new XMLHttpRequest()<br />

Next, make the cross-origin XMLHttpRequest by specifying an address on a different origin as<br />

shown in the following example.<br />

crossOriginRequest.open("GET", "http://www.example.net/stockfeed", true);<br />

Make sure, you listen for errors. There are many reasons why this request might not succeed. For<br />

example, network failure, access denied, and lack of CORS support on the target server.<br />

Using <strong>Pro</strong>gress Events<br />

Instead of numerical states representing different stages of the request and response, XMLHttpRequest<br />

Level 2 provides named progress events. You can listen for each of these events by setting a callback<br />

function for the event handler attribute.<br />

Listing 5-8 shows how callback functions are used to handle progress events. <strong>Pro</strong>gress events have<br />

fields for the total amount of data to transfer, the amount that has already transferred, and a Boolean<br />

value indicating whether the total is known (it may not be in the case of streaming HTTP).<br />

XMLHttpRequest.upload dispatches events with the same fields.<br />

Listing 5-8. Using the onprogress event<br />

crossOriginRequest.onprogress = function(e) {<br />

var total = e.total;<br />

var loaded = e.loaded;<br />

}<br />

if (e.lengthComputable) {<br />

// do something with the progress information<br />

}

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

Saved successfully!

Ooh no, something went wrong!