Skip to main content

Bug Tracker

Side navigation

#5718 closed enhancement (fixed)

Opened December 26, 2009 09:18PM UTC

Closed January 06, 2010 03:20PM UTC

$.ajax() - dataType: "auto" setting for auto-detecting/parsing response data via content-type header

Reported by: webbiedave Owned by:
Priority: major Milestone: 1.4
Component: ajax Version: 1.4a2
Keywords: ajax, dataType, detection, auto-detection, content-type Cc:
Blocked by: Blocking:
Description

When dataType is set to "auto", the response Content-Type header will be used to determine the type of data received (xml, html, script, json, text). If the header is javascript or json, the data will be evaluated/parsed.

This allows multiple expected dataTypes.

httpData: function( xhr, type, s ) {
	var ct = xhr.getResponseHeader("content-type"),
		xml = type === "xml" || (!type || type === "auto") && ct && ct.indexOf("xml") >= 0,
		data = xml ? xhr.responseXML : xhr.responseText;

	if ( xml && data.documentElement.nodeName === "parsererror" ) {
		throw "parsererror";
	}

	// Allow a pre-filtering function to sanitize the response
	// s is checked to keep backwards compatibility
	if ( s && s.dataFilter ) {
		data = s.dataFilter( data, type );
	}

	// The filter can actually parse the response
	if ( typeof data === "string" ) {

		// If the type is "script", eval it in global context
		if ( type === "script" || (type === "auto" && ct && ct.indexOf("javascript") >= 0) ) {
			jQuery.globalEval( data );
		}

		// Get the JavaScript object, if JSON is used.
		if ( type === "json" || (type === "auto" && ct && ct.indexOf("json") >= 0) ) {
			if ( typeof JSON === "object" && JSON.parse ) {
				data = JSON.parse( data );
			} else {
				data = (new Function("return " + data))();
			}
		}
	}

	return data;
}
Attachments (0)
Change History (2)

Changed December 29, 2009 05:02PM UTC by webbiedave comment:1

Future detection and translation functionality will not be limited to the data types currently accepted by jQuery.ajax(). Future data types will also be auto-detected and translated. Therefore, it is imperative that any ajax calls using this setting are connected to trusted and competent servers in order to ensure safe action.

If you are expecting only xml or html to be returned, you should continue using dataType: xml/html/null.

Changed January 06, 2010 03:20PM UTC by john comment:2

resolution: → fixed
status: newclosed

I opted to not land the "auto" setting (not providing a dataType value is the same as providing "auto") but I did land content-type sniffing support for scripts:

http://github.com/jquery/jquery/commit/6861b5d4eb16222ed5ea623af6ce75362b55d1d4

Thanks for the recommendation!