Commit a938d7b1 authored by Richard Gibson's avatar Richard Gibson

No ticket: compress ajax. Close gh-1041.

parent c27dc018
...@@ -3,17 +3,16 @@ var ...@@ -3,17 +3,16 @@ var
ajaxLocParts, ajaxLocParts,
ajaxLocation, ajaxLocation,
antiCacheValue = jQuery.now(), ajax_nonce = jQuery.now(),
ajax_rquery = /\?/,
rhash = /#.*$/, rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection // #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/, rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//, rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method // Keep a copy of the old load method
...@@ -38,7 +37,7 @@ var ...@@ -38,7 +37,7 @@ var
transports = {}, transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"]; allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing // #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set // a field from window.location if document.domain has been set
...@@ -66,24 +65,22 @@ function addToPrefiltersOrTransports( structure ) { ...@@ -66,24 +65,22 @@ function addToPrefiltersOrTransports( structure ) {
dataTypeExpression = "*"; dataTypeExpression = "*";
} }
var dataType, list, placeBefore, var dataType,
dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ),
i = 0, i = 0,
length = dataTypes.length; dataTypes = dataTypeExpression.toLowerCase().split( core_rspace );
if ( jQuery.isFunction( func ) ) { if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression // For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) { while ( (dataType = dataTypes[i++]) ) {
dataType = dataTypes[ i ]; // Prepend if requested
// We control if we're asked to add before if ( dataType[0] === "+" ) {
// any existing element dataType = dataType.slice( 1 ) || "*";
placeBefore = /^\+/.test( dataType ); (structure[ dataType ] = structure[ dataType ] || []).unshift( func );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*"; // Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
} }
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
} }
} }
}; };
...@@ -120,14 +117,17 @@ function inspectPrefiltersOrTransports( structure, options, originalOptions, jqX ...@@ -120,14 +117,17 @@ function inspectPrefiltersOrTransports( structure, options, originalOptions, jqX
function ajaxExtend( target, src ) { function ajaxExtend( target, src ) {
var key, deep, var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {}; flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) { for ( key in src ) {
if ( src[ key ] !== undefined ) { if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
} }
} }
if ( deep ) { if ( deep ) {
jQuery.extend( true, target, deep ); jQuery.extend( true, target, deep );
} }
return target;
} }
jQuery.fn.load = function( url, params, callback ) { jQuery.fn.load = function( url, params, callback ) {
...@@ -135,11 +135,6 @@ jQuery.fn.load = function( url, params, callback ) { ...@@ -135,11 +135,6 @@ jQuery.fn.load = function( url, params, callback ) {
return _load.apply( this, arguments ); return _load.apply( this, arguments );
} }
// Don't do a request if no elements are being requested
if ( !this.length ) {
return this;
}
var selector, type, response, var selector, type, response,
self = this, self = this,
off = url.indexOf(" "); off = url.indexOf(" ");
...@@ -161,49 +156,41 @@ jQuery.fn.load = function( url, params, callback ) { ...@@ -161,49 +156,41 @@ jQuery.fn.load = function( url, params, callback ) {
type = "POST"; type = "POST";
} }
// Request the remote document // If we have elements to modify, make the request
jQuery.ajax({ if ( self.length > 0 ) {
url: url, jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params,
complete: function( jqXHR, status ) {
if ( callback ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
}
}
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
// See if a selector was specified // if "type" variable is undefined, then "GET" method will be used
self.html( selector ? type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Create a dummy div to hold the results // Save response for use in complete callback
jQuery("<div>") response = arguments;
// inject the contents of the document in, removing the scripts self.html( selector ?
// to avoid any 'Permission Denied' errors in IE
.append( responseText.replace( rscript, "" ) )
// Locate the specified elements // If a selector was specified, locate the right elements in a dummy div
.find( selector ) : // Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// If not, just inject the full result // Otherwise use the full result
responseText ); responseText );
}); }).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this; return this;
}; };
// Attach a bunch of functions for handling common AJAX events // Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){
jQuery.fn[ o ] = function( f ){ jQuery.fn[ type ] = function( fn ){
return this.on( o, f ); return this.on( type, fn );
}; };
}); });
...@@ -217,50 +204,32 @@ jQuery.each( [ "get", "post" ], function( i, method ) { ...@@ -217,50 +204,32 @@ jQuery.each( [ "get", "post" ], function( i, method ) {
} }
return jQuery.ajax({ return jQuery.ajax({
type: method,
url: url, url: url,
type: method,
dataType: type,
data: data, data: data,
success: callback, success: callback
dataType: type
}); });
}; };
}); });
jQuery.extend({ jQuery.extend({
getScript: function( url, callback ) { // Counter for holding the number of active queries
return jQuery.get( url, undefined, callback, "script" ); active: 0,
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target; // Last-Modified header cache for next request
}, lastModified: {},
etag: {},
ajaxSettings: { ajaxSettings: {
url: ajaxLocation, url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true, global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: true, processData: true,
async: true, async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/* /*
timeout: 0, timeout: 0,
data: null, data: null,
...@@ -274,11 +243,11 @@ jQuery.extend({ ...@@ -274,11 +243,11 @@ jQuery.extend({
*/ */
accepts: { accepts: {
xml: "application/xml, text/xml", "*": allTypes,
html: "text/html",
text: "text/plain", text: "text/plain",
json: "application/json, text/javascript", html: "text/html",
"*": allTypes xml: "application/xml, text/xml",
json: "application/json, text/javascript"
}, },
contents: { contents: {
...@@ -292,9 +261,8 @@ jQuery.extend({ ...@@ -292,9 +261,8 @@ jQuery.extend({
text: "responseText" text: "responseText"
}, },
// List of data converters // Data converters
// 1) key format is "source_type destination_type" (a single space in-between) // Keys separate source (or catchall "*") and destination types with a single space
// 2) the catchall symbol "*" can be used for source_type
converters: { converters: {
// Convert anything to text // Convert anything to text
...@@ -315,11 +283,24 @@ jQuery.extend({ ...@@ -315,11 +283,24 @@ jQuery.extend({
// and when you create one that shouldn't be // and when you create one that shouldn't be
// deep extended (see ajaxExtend) // deep extended (see ajaxExtend)
flatOptions: { flatOptions: {
context: true, url: true,
url: true context: true
} }
}, },
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ), ajaxTransport: addToPrefiltersOrTransports( transports ),
...@@ -335,13 +316,12 @@ jQuery.extend({ ...@@ -335,13 +316,12 @@ jQuery.extend({
// Force options to be an object // Force options to be an object
options = options || {}; options = options || {};
var // ifModified key var transport,
// ifModified key
ifModifiedKey, ifModifiedKey,
// Response headers // Response headers
responseHeadersString, responseHeadersString,
responseHeaders, responseHeaders,
// transport
transport,
// timeout handle // timeout handle
timeoutTimer, timeoutTimer,
// Cross-domain detection vars // Cross-domain detection vars
...@@ -354,15 +334,13 @@ jQuery.extend({ ...@@ -354,15 +334,13 @@ jQuery.extend({
s = jQuery.ajaxSetup( {}, options ), s = jQuery.ajaxSetup( {}, options ),
// Callbacks context // Callbacks context
callbackContext = s.context || s, callbackContext = s.context || s,
// Context for global events // Context for global events is callbackContext if it is a DOM node or jQuery collection
// It's the callbackContext if one was provided in the options globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
// and if it's a DOM node or a jQuery collection jQuery( callbackContext ) :
globalEventContext = callbackContext !== s && jQuery.event,
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds // Deferreds
deferred = jQuery.Deferred(), deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ), completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks // Status-dependent callbacks
statusCode = s.statusCode || {}, statusCode = s.statusCode || {},
// Headers (they are sent all at once) // Headers (they are sent all at once)
...@@ -374,37 +352,36 @@ jQuery.extend({ ...@@ -374,37 +352,36 @@ jQuery.extend({
strAbort = "canceled", strAbort = "canceled",
// Fake xhr // Fake xhr
jqXHR = { jqXHR = {
readyState: 0, readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed // Builds headers hashtable if needed
getResponseHeader: function( key ) { getResponseHeader: function( key ) {
var match; var match;
if ( state === 2 ) { if ( state === 2 ) {
if ( !responseHeaders ) { if ( !responseHeaders ) {
responseHeaders = {}; responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) { while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
} }
} }
match = responseHeaders[ key.toLowerCase() ]; match = responseHeaders[ key.toLowerCase() ];
} }
return match === undefined ? null : match; return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
}, },
// Overrides response content-type header // Overrides response content-type header
...@@ -415,148 +392,38 @@ jQuery.extend({ ...@@ -415,148 +392,38 @@ jQuery.extend({
return this; return this;
}, },
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request // Cancel the request
abort: function( statusText ) { abort: function( statusText ) {
statusText = statusText || strAbort; var finalText = statusText || strAbort;
if ( transport ) { if ( transport ) {
transport.abort( statusText ); transport.abort( finalText );
} }
done( 0, statusText ); done( 0, finalText );
return this; return this;
} }
}; };
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ ifModifiedKey ] = modified;
}
modified = jqXHR.getResponseHeader("Etag");
if ( modified ) {
jQuery.etag[ ifModifiedKey ] = modified;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
isSuccess = ajaxConvert( s, response );
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds // Attach deferreds
deferred.promise( jqXHR ); deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done; jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail; jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for ( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.always( tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion) // Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
...@@ -593,23 +460,23 @@ jQuery.extend({ ...@@ -593,23 +460,23 @@ jQuery.extend({
// We can fire global events as of now if asked to // We can fire global events as of now if asked to
fireGlobals = s.global; fireGlobals = s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type // Uppercase the type
s.type = s.type.toUpperCase(); s.type = s.type.toUpperCase();
// Determine if request has content // Determine if request has content
s.hasContent = !rnoContent.test( s.type ); s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content // More options handling for requests with no content
if ( !s.hasContent ) { if ( !s.hasContent ) {
// If data is available, append data to url // If data is available, append data to url
if ( s.data ) { if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry // #9682: remove data so that it's not used in an eventual retry
delete s.data; delete s.data;
} }
...@@ -619,21 +486,16 @@ jQuery.extend({ ...@@ -619,21 +486,16 @@ jQuery.extend({
// Add anti-cache in url if needed // Add anti-cache in url if needed
if ( s.cache === false ) { if ( s.cache === false ) {
s.url = rts.test( ifModifiedKey ) ?
var ts = antiCacheValue++, // If there is already a '_' parameter, set its value
// try replacing _= if it is there ifModifiedKey.replace( rts, "$1_=" + ajax_nonce++ ) :
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end // Otherwise add one to the end
s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); ifModifiedKey + ( ajax_rquery.test( ifModifiedKey ) ? "&" : "?" ) + "_=" + ajax_nonce++;
} }
} }
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) { if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url; ifModifiedKey = ifModifiedKey || s.url;
...@@ -645,6 +507,11 @@ jQuery.extend({ ...@@ -645,6 +507,11 @@ jQuery.extend({
} }
} }
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType // Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader( jqXHR.setRequestHeader(
"Accept", "Accept",
...@@ -681,21 +548,22 @@ jQuery.extend({ ...@@ -681,21 +548,22 @@ jQuery.extend({
done( -1, "No Transport" ); done( -1, "No Transport" );
} else { } else {
jqXHR.readyState = 1; jqXHR.readyState = 1;
// Send global event // Send global event
if ( fireGlobals ) { if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
} }
// Timeout // Timeout
if ( s.async && s.timeout > 0 ) { if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){ timeoutTimer = setTimeout(function() {
jqXHR.abort( "timeout" ); jqXHR.abort("timeout");
}, s.timeout ); }, s.timeout );
} }
try { try {
state = 1; state = 1;
transport.send( requestHeaders, done ); transport.send( requestHeaders, done );
} catch (e) { } catch ( e ) {
// Propagate exception as error if not done // Propagate exception as error if not done
if ( state < 2 ) { if ( state < 2 ) {
done( -1, e ); done( -1, e );
...@@ -706,16 +574,121 @@ jQuery.extend({ ...@@ -706,16 +574,121 @@ jQuery.extend({
} }
} }
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ ifModifiedKey ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ ifModifiedKey ] = modified;
}
}
// If not modified
if ( status === 304 ) {
isSuccess = true;
statusText = "notmodified";
// If we have data
} else {
isSuccess = ajaxConvert( s, response );
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR; return jqXHR;
}, },
// Counter for holding the number of active queries getScript: function( url, callback ) {
active: 0, return jQuery.get( url, undefined, callback, "script" );
},
// Last-Modified header cache for next request
lastModified: {},
etag: {}
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
}
}); });
/* Handles responses to an ajax request: /* Handles responses to an ajax request:
...@@ -741,7 +714,7 @@ function ajaxHandleResponses( s, jqXHR, responses ) { ...@@ -741,7 +714,7 @@ function ajaxHandleResponses( s, jqXHR, responses ) {
while( dataTypes[ 0 ] === "*" ) { while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift(); dataTypes.shift();
if ( ct === undefined ) { if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
} }
} }
...@@ -788,11 +761,11 @@ function ajaxHandleResponses( s, jqXHR, responses ) { ...@@ -788,11 +761,11 @@ function ajaxHandleResponses( s, jqXHR, responses ) {
function ajaxConvert( s, response ) { function ajaxConvert( s, response ) {
var conv, conv2, current, tmp, var conv, conv2, current, tmp,
converters = {},
i = 0,
// Work with a copy of dataTypes in case we need to modify it for conversion // Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice(), dataTypes = s.dataTypes.slice(),
prev = dataTypes[ 0 ], prev = dataTypes[ 0 ];
converters = {},
i = 0;
// Apply the dataFilter if provided // Apply the dataFilter if provided
if ( s.dataFilter ) { if ( s.dataFilter ) {
......
var oldCallbacks = [], var oldCallbacks = [],
rquestion = /\?/, rjsonp = /(=)\?(?=&|$)|\?\?/;
rjsonp = /(=)\?(?=&|$)|\?\?/,
nonce = jQuery.now();
// Default jsonp settings // Default jsonp settings
jQuery.ajaxSetup({ jQuery.ajaxSetup({
jsonp: "callback", jsonp: "callback",
jsonpCallback: function() { jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) );
this[ callback ] = true; this[ callback ] = true;
return callback; return callback;
} }
...@@ -17,30 +15,24 @@ jQuery.ajaxSetup({ ...@@ -17,30 +15,24 @@ jQuery.ajaxSetup({
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer, var callbackName, overwritten, responseContainer,
data = s.data, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
url = s.url, "url" :
hasCallback = s.jsonp !== false, typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
replaceInUrl = hasCallback && rjsonp.test( url ), );
replaceInData = hasCallback && !replaceInUrl && typeof data === "string" &&
!( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") &&
rjsonp.test( data );
// Handle iff the expected data type is "jsonp" or we have a parameter to set // Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) { if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it // Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() : s.jsonpCallback() :
s.jsonpCallback; s.jsonpCallback;
overwritten = window[ callbackName ];
// Insert callback into url or form data // Insert callback into url or form data
if ( replaceInUrl ) { if ( jsonProp ) {
s.url = url.replace( rjsonp, "$1" + callbackName ); s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( replaceInData ) { } else if ( s.jsonp !== false ) {
s.data = data.replace( rjsonp, "$1" + callbackName ); s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
} else if ( hasCallback ) {
s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
} }
// Use data converter to retrieve json after script execution // Use data converter to retrieve json after script execution
...@@ -55,6 +47,7 @@ jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { ...@@ -55,6 +47,7 @@ jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
s.dataTypes[ 0 ] = "json"; s.dataTypes[ 0 ] = "json";
// Install callback // Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() { window[ callbackName ] = function() {
responseContainer = arguments; responseContainer = arguments;
}; };
......
...@@ -4,7 +4,7 @@ jQuery.ajaxSetup({ ...@@ -4,7 +4,7 @@ jQuery.ajaxSetup({
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
}, },
contents: { contents: {
script: /javascript|ecmascript/ script: /(?:java|ecma)script/
}, },
converters: { converters: {
"text script": function( text ) { "text script": function( text ) {
...@@ -32,13 +32,13 @@ jQuery.ajaxTransport( "script", function(s) { ...@@ -32,13 +32,13 @@ jQuery.ajaxTransport( "script", function(s) {
if ( s.crossDomain ) { if ( s.crossDomain ) {
var script, var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; head = document.head || jQuery("head")[0] || document.documentElement;
return { return {
send: function( _, callback ) { send: function( _, callback ) {
script = document.createElement( "script" ); script = document.createElement("script");
script.async = true; script.async = true;
...@@ -57,12 +57,12 @@ jQuery.ajaxTransport( "script", function(s) { ...@@ -57,12 +57,12 @@ jQuery.ajaxTransport( "script", function(s) {
script.onload = script.onreadystatechange = null; script.onload = script.onreadystatechange = null;
// Remove the script // Remove the script
if ( head && script.parentNode ) { if ( script.parentNode ) {
head.removeChild( script ); script.parentNode.removeChild( script );
} }
// Dereference the script // Dereference the script
script = undefined; script = null;
// Callback if not abort // Callback if not abort
if ( !isAbort ) { if ( !isAbort ) {
...@@ -70,14 +70,15 @@ jQuery.ajaxTransport( "script", function(s) { ...@@ -70,14 +70,15 @@ jQuery.ajaxTransport( "script", function(s) {
} }
} }
}; };
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378). // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild ); head.insertBefore( script, head.firstChild );
}, },
abort: function() { abort: function() {
if ( script ) { if ( script ) {
script.onload( 0, 1 ); script.onload( undefined, true );
} }
} }
}; };
......
var xhrCallbacks, var xhrCallbacks, xhrSupported,
xhrId = 0,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload // #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() { xhrOnUnloadAbort = window.ActiveXObject && function() {
// Abort all pending requests // Abort all pending requests
for ( var key in xhrCallbacks ) { var key;
xhrCallbacks[ key ]( 0, 1 ); for ( key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
} }
} : false, };
xhrId = 0;
// Functions to create xhrs // Functions to create xhrs
function createStandardXHR() { function createStandardXHR() {
...@@ -17,7 +18,7 @@ function createStandardXHR() { ...@@ -17,7 +18,7 @@ function createStandardXHR() {
function createActiveXHR() { function createActiveXHR() {
try { try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" ); return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch( e ) {} } catch( e ) {}
} }
...@@ -37,15 +38,12 @@ jQuery.ajaxSettings.xhr = window.ActiveXObject ? ...@@ -37,15 +38,12 @@ jQuery.ajaxSettings.xhr = window.ActiveXObject ?
createStandardXHR; createStandardXHR;
// Determine support properties // Determine support properties
(function( xhr ) { xhrSupported = jQuery.ajaxSettings.xhr();
jQuery.extend( jQuery.support, { jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
ajax: !!xhr, xhrSupported = jQuery.support.ajax = !!xhrSupported;
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr // Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) { if ( xhrSupported ) {
jQuery.ajaxTransport(function( s ) { jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest // Cross domain only allowed if supported through XMLHttpRequest
...@@ -86,7 +84,7 @@ if ( jQuery.support.ajax ) { ...@@ -86,7 +84,7 @@ if ( jQuery.support.ajax ) {
// (it can always be set on a per-request basis or even using ajaxSetup) // (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided. // For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) { if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest"; headers["X-Requested-With"] = "XMLHttpRequest";
} }
// Need an extra try/catch for cross domain requests in Firefox 3 // Need an extra try/catch for cross domain requests in Firefox 3
...@@ -136,10 +134,10 @@ if ( jQuery.support.ajax ) { ...@@ -136,10 +134,10 @@ if ( jQuery.support.ajax ) {
xhr.abort(); xhr.abort();
} }
} else { } else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {}; responses = {};
status = xhr.status;
xml = xhr.responseXML; xml = xhr.responseXML;
responseHeaders = xhr.getAllResponseHeaders();
// Construct response list // Construct response list
if ( xml && xml.documentElement /* #4958 */ ) { if ( xml && xml.documentElement /* #4958 */ ) {
...@@ -211,7 +209,7 @@ if ( jQuery.support.ajax ) { ...@@ -211,7 +209,7 @@ if ( jQuery.support.ajax ) {
abort: function() { abort: function() {
if ( callback ) { if ( callback ) {
callback(0,1); callback( undefined, true );
} }
} }
}; };
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment