Sometimes you don't know what type of document the server is going to return, so it would be nice to have the ajax handler deal with the response as the server is directing it to.
JQuery doesn't have this baked in (I have had a ticket for ages there to implement it), but a workaround is to roll your own handler. The data filter that was introduced in the latest round of jquery is useless since you don't have access to the response object (and thus the header) and doing hacky string parsing was brittle. To replace the current handler, just roll your own httpData function that replaces the native function in jquery.
Using jquery 1.2.6 + here is a patch you can add after the jquery reference on your page:
* patch for dynamic evaluation of xhr responseType to set the dataType on jQuery */
jQuery.extend({
httpData: function( xhr, type, s ) {
var ct = xhr.getResponseHeader("content-type"),
xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
script = type == "script" || !type && ct && ct.indexOf("script") >= 0,
json = type == "json" || !type && ct && ct.indexOf("json") >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
if ( xml && data.documentElement.tagName == "parsererror" )
throw "parsererror";
// Allow a pre-filtering function to sanitize the response
// s != null is checked to keep backwards compatibility
if( s && s.dataFilter )
data = s.dataFilter( data, type );
// If the type is "script", eval it in global context
if ( script )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( json )
data = eval("(" + data + ")");
return data;
}
});
All this is doing is what it already does with xml response types...it sniffs the response header and handles appropriately. Now I can let my server determine whether I am generating just some javascript snippet that should get evaluated or some markup that should be pushed into the page without requiring my client ajax method to state it explicitly.
Posted
10-14-2008 8:40 PM
by
Michael Nichols