Thursday, October 28, 2010

Load local XML through AJAX request problems in IE

Have you got a simple html-js-xml project (doesn't need a server) that works locally on firefox but not in IE? You're welcome!
Understanding the problem
Let's see my example... I had an html document which only charges an external javascript which has the due to load an xml file representing a flowchart and simulate a navigation through the tree, with conditional steps and forwards steps.
Even if I'm a mootools lover, for this project I used jQuery because the mootools core 1.2.x xml loader doesn't work for IE in any case.
So I used jQuery ajax method to load the xml this way:
var xml = $.ajax({
    async: false,
    type:"GET",
    context: this,
    url: chart_path,
    dataType:"xml"
}).responseXML;
Now, I thought at my xml variable as a DOM object over which use all the traversing methods implemented by jQuery. That was true... in some cases.
The scenario
- Application hosted on a server
  works if visited with any browser and any OS
- Application hosted on my local server running on Ubuntu 9.04
  works if visited with any browser and any OS
- Application hosted on a PC with Windows XP not under a server
  works with firefox but not with IE
OH MY GOD
The answer
So at the end I gained the solution. The problem is that I was trying to get the responseXML from the ajax object, but without a server "telling" the browser that yes, that content is really an XML. Moreover (OH OH) IE is not so intelligent as to understand this things without help.
The solution
So what may we do? Simple. We get not the responseXML but the responseText and then load it using the loadXML method of the ActiveXObject. What follow is my example code
var xmltext = $.ajax({
    async: false,
    type:"GET",
    context: this,
    url: chart_path,
    dataType:"xml"
}).responseText;

if($.browser.msie) {
    xml = new ActiveXObject("Microsoft.XMLDOM");
    xml.loadXML(xmltext);
}
else {
    parser = new DOMParser();
    xml = parser.parseFromString(xmltext, "text/xml");
}
Now my xml variable is ready and contains the desired XML object.
Saludos

No comments: