Bug Tracker

Opened 10 years ago

Closed 10 years ago

#5718 closed enhancement (fixed)

$.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;
}

Change History (2)

comment:1 Changed 10 years ago by webbiedave

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.

comment:2 Changed 10 years ago by john

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!

Note: See TracTickets for help on using tickets.