Using an XML Library


var result = xsltProcess(xml, xslt); 

As you can see, using XSLT from JavaScript can be quite tricky if it is to work on as many browsers as possible. In this case, using an external framework can really save a lot of time and effort.

Google has created such a framework ("AJAXSLT") which is available free (under a BSD license) at http://goog-ajaxslt.sourceforge.net/. The following phrase uses version 0.4 of the framework, which you can also see from the paths used in the code. The framework itself is also not part of the source code downloads for this book.

The following phrase does the XSLT transformation, but this time relies on the functionality offered by AJAXSLT.

Using XSLT with JavaScript and AJAXSLT (ajaxslt.html)

<script language="JavaScript"   type="text/javascript" src="xmlhttp.js"></script> <script src="/books/3/490/1/html/2/ajaxslt-0.4/misc.js"   type="text/javascript"></script> <script src="/books/3/490/1/html/2/ajaxslt-0.4/dom.js"   type="text/javascript"></script> <script src="/books/3/490/1/html/2/ajaxslt-0.4/xpath.js"   type="text/javascript"></script> <script src="/books/3/490/1/html/2/ajaxslt-0.4/xslt.js"   type="text/javascript"></script> <script language="JavaScript"   type="text/javascript"> var xml = null; var xslt = null; var XMLHttp1 = getXMLHttp(); var XMLHttp2 = getXMLHttp(); window.onload = function() {   XMLHttp1.open("GET", "phrasebooks.xml");   XMLHttp1.onreadystatechange = handlerFunction1;   XMLHttp1.send(null);   XMLHttp2.open("GET", "phrasebooks.xsl");   XMLHttp2.onreadystatechange = handlerFunction2;   XMLHttp2.send(null); } function handlerFunction1() {   if (XMLHttp1.readyState == 4) {     xml = xmlParse(XMLHttp1.responseText);     if (xslt != null) {       transform();     }   } } function handlerFunction2() {   if (XMLHttp2.readyState == 4) {     xslt = xmlParse(XMLHttp2.responseText);     if (xml != null) {       transform();     }   } } function transform() {   var result = xsltProcess(xml, xslt);   document.getElementById("output").innerHTML =     result; } </script> <div ></div> 

This not only works fine (as you can see, most of the code is "spent" for loading the XML and XSL files), but also works cross-browser, as Figure 11.5 (shot in Konqueror) demonstrates. Another nice feature: You can also use XPath with this library. Both Internet Explorer and Mozilla browsers and Opera work with XPath, but in an even more incompatible way than they do regarding XSLT. Also, the AJAXSLT XPath support can deal with other browsers, as well.

Figure 11.5. With AJAXLST the transformation even works in Konqueror.





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