AJAX - The Complete Reference

(avery) #1

166 Part I: Core Ideas


Now fetch the two needed documents, the bookmarks.xml file and the bookmarks.xsl
file. Note in the sendRequest() function the callback function creates another XHR
(xhrSS), which then fetches the required style sheet:

function sendRequest()
{
var url = "http://ajaxref.com/ch4/bookmarks.xml";
var xhr = createXHR();

if (xhr)
{
xhr.open("GET",url,true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200)
{
var xhrSS = createXHR();
if (xhrSS)
{
xhrSS.open("GET",
"http://ajaxref.com/ch4/bookmarks.xsl", true);
xhrSS.onreadystatechange =
function(){handleResponse(xhr, xhrSS);}
xhrSS.send(null);
}
}
}
xhr.send(null);
}
}

Once the second XHR request has returned with the style sheet, it will send both the
XHR that fetched the XML and the one fetching the XSL on to the handleResponse()
callback function. In handleResponse(), you use the Firefox-like syntax that Sarissa makes
work in all browsers to instantiate an XSLTProcessor object, load the style sheet, and then
apply that to the bookmark XML data found in xhr.responseXML. Once you have your
nicely formatted table, you use the DOM and append it to the document:

function handleResponse(xhr, xhrSS)
{
if (xhrSS.readyState == 4 && xhrSS.status == 200)
{
var responseOutput = document.getElementById("responseOutput");
var xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xhrSS.responseXML);
var resultDocument = xsltProcessor.transformToFragment(xhr.responseXML,
document);
responseOutput.appendChild(resultDocument);
}
}

The Sarissa-based cross-browser version of the bookmarks table using XSLT can be
found at http://ajaxref.com/ch4/xmlxsltsarissa.html. Alternatively, a Google AJAXSLT
version can be found at http://ajaxref.com/ch4/xmlxsltgoogle.html.
Free download pdf