tadhg.com
tadhg.com
 

Making AJAX Treat Text as XML

15:05 Mon 06 Nov 2006
[, , , ]

JavaScript can be really picky about what it accepts as “XML”, and in most AJAX uses it requires that the server send it something with the correct MIME type. This can get really annoying if you’re trying to deal with local XML from your filesystem, because the browser will treat it as text, and the AJAX functions will error out. So, I finally decided I’d had enough, started looking into using the DOMParser, discovered it didn’t exist in IE, and then found a post about a DOMParser for IE and Safari.

The function I now drop into my namespace objects looks like this:

stringToXml : function(string) {
if (typeof(string) == “string”) {
if (typeof DOMParser == “undefined”) {
DOMParser = function () {}
DOMParser.prototype.parseFromString = function (string, contentType) {
if (typeof ActiveXObject != “undefined”) {
var d = new ActiveXObject(“MSXML.DomDocument”);
d.loadXML(string);
return d;
} else if (typeof XMLHttpRequest != “undefined”) {
var req = new XMLHttpRequest;
req.open(“GET”, “data:” + (contentType || “application/xml”) + “;charset=utf-8,” + encodeURIComponent(string), false);
if (req.overrideMimeType) {
req.overrideMimeType(contentType);
}
req.send(null);
return req.responseXML;
}
}
}
return (new DOMParser()).parseFromString(string, “text/xml”);
}
else {
return (string)
}
}

It could probably be more robust, but right now I’m satisfied with: “transform strings to XML and leave XML alone”.

Leave a Reply