14.08.2016 Views

Beginning JavaScript with DOM Scripting and Ajax, 2nd Edition

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

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

CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js<br />

■ Note These links are not totally unobtrusive <strong>and</strong> up to the st<strong>and</strong>ard of the rest of the code examples in this book,<br />

but at least they work <strong>with</strong>out javascript—the browser will simply show the text files when scripting is not available.<br />

It is very tempting, especially when using out-of-the-box <strong>Ajax</strong> libraries, to create scripting-dependent links. no matter<br />

how cool the technology is, this is never a good idea.<br />

simpleXHR.js<br />

simplexhr = {<br />

doxhr : function( container, url ) {<br />

if( !document.getElementById || !document.createTextNode) {<br />

return;<br />

}<br />

simplexhr.outputContainer = document.getElementById( container );<br />

if( !simplexhr.outputContainer ){ return; }<br />

The script starts by checking for the <strong>DOM</strong> <strong>and</strong> checking whether the element you want to write content into is<br />

available. If the element is available, it gets stored in a property called outputContainer to make it available for all<br />

other methods in the script.<br />

simpleXHR.js (continued)<br />

var request;<br />

try{<br />

request = new XMLHttpRequest();<br />

} catch ( error ) {<br />

try {<br />

request = new ActiveXObject("Microsoft.XMLHTTP" );<br />

} catch ( error ) {<br />

return true;<br />

}<br />

}<br />

Define a new variable called request <strong>and</strong> use the try <strong>and</strong> catch construct to see which XHR version is supported.<br />

Try assigning a new XMLHttpRequest. If that is not supported, an error occurs that triggers the catch statement. (You<br />

can learn more about try <strong>and</strong> catch() in the appendix of this book.) This one tries to assign the Microsoft ActiveX<br />

object instead. If that is not available either, the method returns true, which means the browser will just follow the<br />

link <strong>and</strong> show the text in the browser.<br />

If the assignment was successful, you have a new XMLHttpRequest object at your disposal.<br />

■ Note For a complete list of methods, h<strong>and</strong>lers, <strong>and</strong> properties of the XMLHttpRequest object, you can consult the<br />

documentation at the w3C site: http://www.w3.org/TR/XMLHttpRequest/. You can also refer to the Mozilla developer<br />

network at https://developer.mozilla.org/en-US/docs/<strong>DOM</strong>/XMLHttprequest or the Microsoft web site at<br />

http://msdn.microsoft.com/en-us/library/ms535874%28v=vs.85%29.aspx.<br />

250<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!