Section VII.6. Using XMLHttpRequest for Other Data Types


VII.6. Using XMLHttpRequest for Other Data Types

Despite the "xml" part of its name, the XMLHttpRequest object can retrieve other types of data which can be accessed through the responseText property. This includes HTML source code or any other kind of string, such as a string representation of a JavaScript custom object or array (JSON). Just be aware that data such as HTML source code is strictly in string format, which means that you cannot use DOM parsing on it to extract data that way. You could, of course, write that data into a hidden iframe element, and then use DOM parsing on the document inside the iframe.

But it is the JavaScript Object Notation possibilities that are more intriguing. Instead of having to script your way through an XML document's DOM, have the server output its results as a string representation of the objects and/or arrays that make the client-side scripting most efficient, such as preset associative arrays that facilitate table iterations or client-side lookups. Converting a JSON string to objects entails the JavaScript eval( ) global function. Although I'm generally not a fan of this function because of its detrimental effects on performance, occasional one-shot use (as opposed to repeated usage inside a tight repeat loop) has no impact on performance as perceived by the user. Visit http://www.json.org/js.html for additional details, including a link to a small open source library that provides robust conversion between objects and strings while thwarting the possibilities of executing "evil" code in the browser.

Without question, the XMLHttpRequest object has emerged from its humble, almost hidden, beginnings as an ActiveX control in IE for Windows to become a corner piece of the DHTML jigsaw puzzle. We developers are fortunate that Mozilla, Apple, and Opera have implemented the object across so many browser brands. It invites our imaginations to soar to new heights of application design and user convenience.




Dynamic HTML. The Definitive Reference
Dynamic HTML: The Definitive Reference
ISBN: 0596527403
EAN: 2147483647
Year: 2004
Pages: 120
Authors: Danny Goodman

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net