JavaScript
  Home arrow JavaScript arrow Page 3 - JavaScript and XML
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVASCRIPT

JavaScript and XML
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 16
    2007-08-08

    Table of Contents:
  • JavaScript and XML
  • 21.1.1 Creating a New Document
  • 21.1.2 Loading a Document from the Network
  • 21.1.4 XML Documents from Data Islands

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    JavaScript and XML - 21.1.2 Loading a Document from the Network


    (Page 3 of 4 )

    Chapter 20 showed how to use the XMLHttpRequest object to dynamically issue HTTP requests for text-based documents. When used with XML documents, the responseXML property refers to the parsed representation as a DOM Document object. XMLHttpRequest is nonstandard but widely available and well understood, and is usually the best technique for loading XML documents.

    There is another way, however. An XML Document object created using the tech niques shown in Example 21-1 can load and parse an XML document using a less well-known technique. Example 21-2 shows how it is done. Amazingly, the code is the same in both Mozilla-based browsers and in IE.

    Example 21-2. Loading an XML document synchronously

    /**
     
    * Synchronously load the XML document at the specified URL and
     
    * return it as a Document object
     * /
    XML.load = function(url) {
        // Create a new document with the previously defined function
        var xmldoc = XML.newDocument();
        xmldoc.async = false;  // We want to load synchronously
        xmldoc.load(url);      // Load and parse
        return xmldoc;         // Return the document
    };

    Like XMLHttpRequest, this load() method is nonstandard. It differs from XMLHttpRequest in several important ways. First, it works only with XML documents; XMLHttpRequest can be used to download any kind of text document. Second, it is not restricted to the HTTP protocol. In particular, it can be used to read files from the local filesystem, which is helpful during the testing and development phase of a web application. Third, when used with HTTP, it generates only GET requests and cannot be used to POST data to a web server.

    Like XMLHttpRequest, the load() method can be used asynchronously. In fact, this is the default method of operation unless async property is set to false . Example 21-3 shows an asynchronous version of the XML.load() method.

    Example 21-3. Loading an XML document asynchronously

    /**
     
    * Asynchronously load and parse an XML document from the specified URL.
     
    * When the document is ready, pass it to the specified callback function.
     * This function returns immediately with no return value.
     */
    XML.loadAsync = function(url, callback) {
        var xmldoc = XML.newDocument();

        // If we created the XML document using createDocument, use
        // onload to determine when it is loaded
        if (document.implementation && document.implementation.createDocument) {
            xmldoc.onload = function() { callback(xmldoc); };
        }
        // Otherwise, use onreadystatechange as with XMLHttpRequest
        else {
           
    xmldoc.onreadystatechange = function() {
                if (xmldoc.readyState == 4) callback(xmldoc);
            };
        }

        // Now go start the download and parsing
        xmldoc.load(url);
    };

    21.1.3  Parsing XML Text

    Sometimes, instead of parsing an XML document loaded from the network, you simply want to parse an XML document from a JavaScript string. In Mozilla-based browsers, a DOMParser object is used; in IE, the loadXML() method of the Document object is used. (If you paid attention to the XML.newDocument() code in Example 21-1, you’ve already seen this method used once.)

    Example 21-4 shows a cross-platform XML parsing function that works in Mozilla and IE. For platforms other than these two, it attempts to parse the text by loading it with an XMLHttpRequest from a data: URL.

    Example 21-4. Parsing an XML document

    /**
     
    * Parse the XML document contained in the string argument and return
     * a Document object that represents it.
     */
    XML.parse = function(text) {
       
    if (typeof DOMParser != "undefined") {
            // Mozilla, Firefox, and related browsers
            return (new DOMParser()).parseFromString(text, "application/xml");
       
    }
        else if (typeof ActiveXObject != "undefined") {
           
    // Internet Explorer.
            var doc = XML.newDocument( );   // Create an empty document
            doc.loadXML(text);              //  Parse text into it
            return doc;                     // Return it
        }
       
    else {
            // As a last resort, try loading the document from a data: URL
           
    // This is supposed to work in Safari. Thanks to Manos Batsis and
           
    // his Sarissa library (sarissa.sourceforge.net) for this technique.
           
    var url = "data:text/xml;charset=utf-8," + encodeURIComponent(text);
           
    var request = new XMLHttpRequest();
           
    request.open("GET", url, false);
           
    request.send(null);
           
    return request.responseXML;
       
    }
    };

    More JavaScript Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "JavaScript: The Definitive Guide, Fifth...
     

    Buy this book now. This article is excerpted from chapter 21 of the book JavaScript: The Definitive Guide, Fifth Edition, written by David Flanagan (O'Reilly; ISBN: 0596101996). Check it out today at your favorite bookstore. Buy this book now.

    JAVASCRIPT ARTICLES

    - Using Click Interceptions with a Database-Dr...
    - Using JavaScript Click Interceptions in an I...
    - Using Click Interceptions with JavaScript
    - QuickSort in Action
    - Quicksort
    - Using Mod_Security to Protect Your Server
    - Detecting and Countering Server Intrusions
    - Securing Your Web Server
    - Building a Secure Web Server
    - Protecting the Server
    - Book Review: Learning the Yahoo! User Interf...
    - Dynamically Generate a Selection List in a R...
    - Intergrate DWR into Your Java Web Application
    - Detect Browser Compatibility with the Reques...
    - Using the EXT JS Date Picker Widget






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT