Using XSLT


var process = new XSLTProcessor(); 

Both Internet Explorer and Mozilla browsers do support XSLT from JavaScript. However, the approach is very different. For Microsoft Internet Explorer, once again ActiveX is required (also with Internet Explorer 7). You first load the XSLT file, then the XML (coming from XMLHttpRequest, of course). Finally, the result of the XSL transformation is available as a string and can, for instance, be appended to the page.

Mozilla browsers, on the other hand, use a different approach; they rely exclusively on native object. The result, however, is different from the Internet Explorer implementation. At the end, you get a DOM fragment, which you can append to the current page's DOM.

The following code covers both major browser types:

Using XSLT with JavaScript (xmlhttpxsl.html)

<script language="JavaScript"   type="text/javascript" src="/books/3/490/1/html/2/xmlhttp.js"></script> <script language="JavaScript"   type="text/javascript"> var XMLHttp = getXMLHttp(); window.onload = function() {   XMLHttp.open("GET", "phrasebooks.xml");   XMLHttp.onreadystatechange = handlerFunction;   XMLHttp.send(null); } function handlerFunction() {   if (XMLHttp.readyState == 4) {     var xml = XMLHttp.responseXML;     if (window.ActiveXObject) {       var xslt = new ActiveXObject(         "MSXML2.FreeThreadedDOMDocument");       xslt.async = false;       xslt.load("phrasebooks.xsl");       var template = new ActiveXObject(         "MSXML2.XSLTemplate");       template.stylesheet = xslt;       var process = template.createProcessor();       process.input = xml;       process.transform();       var para = document.createElement("p");       para.innerHTML = process.output;       document.body.appendChild(para);     } else if (window.XSLTProcessor) {       var xslt = document.implementation.createDocument("", "", null);       xslt.async = false;       xslt.load("phrasebooks.xsl");       var process = new XSLTProcessor();       process.importStylesheet(xslt);       var result = process.transformToFragment(         xml, document);       document.body.appendChild(result);     }   } } </script> 

Figure 11.4 shows the output of the transformation: The data in the XML file is presented as a bulleted list.

Figure 11.4. The outcome of the XSL transformation.


As Figure 11.4 also demonstrates, the Opera browser (from version 9 onward) has a compatible XSLT implementation, using the Mozilla approach.




JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

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