XmlHttpRequest
September 11, 2008 at 8:43 pm | In programming | 1 CommentTags: bears_repeating
Last week i found out why it was a piece of cake for JSON to become the X in Ajax. XmlHttpRequest with XML is just a pain. Here’s why.
I wanted to pull data from a feed into a page. The feed is served as application/rss+xml. After a successful XmlHttpRequest, i wanted to retrieve the items form the request object’s responseXML property.
Unfortunately, this didn’t work on IE 6/7. Turns out IE does only parse the response text when the response is served as text/xml. Ok, so we just grab responseText and parse it ourselves. Problem solved.
Hm. It doesn’t work in Konqueror either. Fortunately the trouble with IE led me into the right direction. While Konqueror does parse the response for mime-type application/xml my feed still would end up unparsed.
Of course there’s no cross-browser way of parsing XML. So what i ended up with was:
try {
var items = req.responseXML.documentElement.getElementsByTagName('item');
} catch(e) {
try {
// for IE we have to do the parsing ourselves, because the feed isn't delivered as text/xml ...
var doc = new ActiveXObject("Microsoft.XMLDOM");
doc.loadXML(req.responseText);
var items = doc.documentElement.getElementsByTagName('item');
} catch(e) {
try {
// ... same for Konqueror
var p = new DOMParser();
var doc = p.parseFromString(req.responseText, "text/xml");
var items = doc.documentElement.getElementsByTagName('item');
} catch(e) {
// well, at least we'll get the title later
var items = [];
}
}
}
And don’t get me started on handling namespaced XML …
1 Comment »
RSS feed for comments on this post. TrackBack URI
Leave a comment
Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.



Thank you indeed. I hope I’m ok to use your solution.
Comment by Erik — August 5, 2009 #