102 Part I: Core Ideas
Managing MIME Types
It is very important for Ajax applications that any called server-side code correctly set the
MIME type of the returned data. You must always remember if the XHR object receives a
data stream with a Content-type: header not set to text/xml, it shouldn’t try to parse
and populate the responseXML property. If that happens and you go ahead and try to
access that property anyway and perform DOM manipulations, you will raise a JavaScript
exception. If content is being retrieved that is truly a particular MIME type (like text/
xml) and for some reason can’t be set properly server-side, it is possible to rectify this in
Firefox and Opera by using the overrideMimeType() method. Usage is fairly simple; set
this method to indicate the desired MIME type before sending the request, and it will
always treat the response as the MIME type specified, regardless of what it is. This is
demonstrated here:
var xhr = createXHR();
if (xhr)
{
xhr.open("GET", url, true);
xhr.overrideMimeType("text/xml");
xhr.onreadystatechange = function(){handleResponse(xhr);};
xhr.send(null);
}
The communications trace here shows that the browser is passed content with format
text/plain that is then overriden to text/xml so that it is parsed.