- 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 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="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.