Loading XML into a page with xmlHttpRequest
Using javascript to talk to the server can be useful for complex applications that need to make multiple small requests to the server and make it fast. By doing this you can keep most of the logic on the server where it belongs. So it can help prevent the complex client anti-pattern (even worse ishaving basicaly the same code on the client and server side).
I dabbled a little with a xmlhttprequest demo.
In the onclick I call the showFeed function and pass the xml and xsl files as arguments. This is what showFeed looks like:
function showFeed(xmlUrl, xslUrl) {
var feed = document.getElementById('feed');
//clear feed div
while(feed.hasChildNodes()){
feed.removeChild(feed.childNodes[0]);
}
//append new htmlfragment
feed.appendChild(getHtmlFragment(xmlUrl, xslUrl));
}
First it finds the div where the new content will be added. I called it ‘feed’. Then it removes all the old content and adds the new content by calling getHtmlFragment.
function getHtmlFragment(xmlUrl, xslUrl) {
var xslStylesheet;
var xsltProcessor = new XSLTProcessor();
//load the xml file
var xmlSource = getResponseXml(xmlUrl).responseXML;
//load the xsl file into the xslt Processor
xslStylesheet = getResponseXml(xslUrl).responseXML;
xsltProcessor.importStylesheet(xslStylesheet);
return xsltProcessor.transformToFragment(xmlSource, document);
}
function getResponseXml(xmlUrl) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", xmlUrl, false);
xmlHttp.send(null);
return xmlHttp;
}
The function getHtmlFragment loads all XML content by calling getResponseXml and uses xsltProcessor to transform the XML to XHTML.
Using xmlHttpRequest() seems to be all the rage and we’ll be seeing a lot more examples.