- Initializing an AJAX Application
- Sending a GET Request
- Sending a POST Request
- Sending a Synchronous Request
- Receiving Multiple Data from the Server
- Aborting an HTTP Request
- Retrieving HTTP Headers
- Receiving XML from the Server
- Using JSON for Data (De)Serialization
- Creating a Waiting Screen
- Solving the Bookmark Problem
- Solving the Back Button Problem
- Using XSLT
- Using an XML Library
- Using the Yahoo! Web Service
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="ajaxslt-0.4/misc.js" type="text/javascript"></script> <script src="ajaxslt-0.4/dom.js" type="text/javascript"></script> <script src="ajaxslt-0.4/xpath.js" type="text/javascript"></script> <script src="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 id="output"></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.