X-Git-Url: http://git.asbjorn.biz/?p=jquery.git;a=blobdiff_plain;f=src%2Fajax.js;h=2d20040a932cac766ed60d84be17635d2724cf5f;hp=bc3696ee8e5c9e133a28b89fcb0517bd18aa80bf;hb=e3cc440934fcb03bfeb10fb6281615409ad6f483;hpb=ee22c8b34bb801f26cacc67a1a3a0ac595fe7928 diff --git a/src/ajax.js b/src/ajax.js index bc3696e..2d20040 100644 --- a/src/ajax.js +++ b/src/ajax.js @@ -7,15 +7,13 @@ var r20 = /%20/g, rheaders = /^(.*?):\s*(.*?)\r?$/mg, // IE leaves an \r character at EOL rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, rnoContent = /^(?:GET|HEAD)$/, + rprotocol = /^\/\//, rquery = /\?/, rscript = /)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rspacesAjax = /\s+/, rts = /([?&])_=[^&]*/, - rurl = /^(\w+:)?\/\/([^\/?#:]+)(?::(\d+))?/, - - // Slice function - sliceFunc = Array.prototype.slice, + rurl = /^(\w+:)\/\/([^\/?#:]+)(?::(\d+))?/, // Keep a copy of the old load method _load = jQuery.fn.load, @@ -36,7 +34,98 @@ var r20 = /%20/g, * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ - transports = {}; + transports = {}, + + // Stored document location array + ajaxLocation; + +// #8138, IE may throw an exception when accessing +// a field from document.location if document.domain has been set +try { + ajaxLocation = document.location.href; +} catch( e ) { + // Use the href attribute of an A element + // since IE will modify it given document.location + ajaxLocation = document.createElement( "a" ); + ajaxLocation.href = ""; + ajaxLocation = ajaxLocation.href; +} + +// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport +function addToPrefiltersOrTransports( structure ) { + + // dataTypeExpression is optional and defaults to "*" + return function( dataTypeExpression, func ) { + + if ( typeof dataTypeExpression !== "string" ) { + func = dataTypeExpression; + dataTypeExpression = "*"; + } + + if ( jQuery.isFunction( func ) ) { + var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ), + i = 0, + length = dataTypes.length, + dataType, + list, + placeBefore; + + // For each dataType in the dataTypeExpression + for(; i < length; i++ ) { + dataType = dataTypes[ i ]; + // We control if we're asked to add before + // any existing element + placeBefore = /^\+/.test( dataType ); + if ( placeBefore ) { + dataType = dataType.substr( 1 ) || "*"; + } + list = structure[ dataType ] = structure[ dataType ] || []; + // then we add to the structure accordingly + list[ placeBefore ? "unshift" : "push" ]( func ); + } + } + }; +} + +//Base inspection function for prefilters and transports +function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, + dataType /* internal */, inspected /* internal */ ) { + + dataType = dataType || options.dataTypes[ 0 ]; + inspected = inspected || {}; + + inspected[ dataType ] = true; + + var list = structure[ dataType ], + i = 0, + length = list ? list.length : 0, + executeOnly = ( structure === prefilters ), + selection; + + for(; i < length && ( executeOnly || !selection ); i++ ) { + selection = list[ i ]( options, originalOptions, jqXHR ); + // If we got redirected to another dataType + // we try there if not done already + if ( typeof selection === "string" ) { + if ( inspected[ selection ] ) { + selection = undefined; + } else { + options.dataTypes.unshift( selection ); + selection = inspectPrefiltersOrTransports( + structure, options, originalOptions, jqXHR, selection, inspected ); + } + } + } + // If we're only executing or nothing was selected + // we try the catchall dataType if not done already + if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { + selection = inspectPrefiltersOrTransports( + structure, options, originalOptions, jqXHR, "*", inspected ); + } + // unnecessary when only executing (prefilters) + // but it'll be ignored by the caller in that case + return selection; +} jQuery.fn.extend({ load: function( url, params, callback ) { @@ -81,14 +170,14 @@ jQuery.fn.extend({ dataType: "html", data: params, // Complete callback (responseText is used internally) - complete: function( jXHR, status, responseText ) { - // Store the response as specified by the jXHR object - responseText = jXHR.responseText; + complete: function( jqXHR, status, responseText ) { + // Store the response as specified by the jqXHR object + responseText = jqXHR.responseText; // If successful, inject the HTML into all the matched elements - if ( jXHR.isResolved() ) { + if ( jqXHR.isResolved() ) { // #4825: Get the actual response in case // a dataFilter is present in ajaxSettings - jXHR.done(function( r ) { + jqXHR.done(function( r ) { responseText = r; }); // See if a selector was specified @@ -107,7 +196,7 @@ jQuery.fn.extend({ } if ( callback ) { - self.each( callback, [ responseText, status, jXHR ] ); + self.each( callback, [ responseText, status, jqXHR ] ); } } }); @@ -186,7 +275,7 @@ jQuery.extend({ }, ajaxSettings: { - url: location.href, + url: ajaxLocation, global: true, type: "GET", contentType: "application/x-www-form-urlencoded", @@ -242,20 +331,14 @@ jQuery.extend({ } }, - ajaxPrefilter: function( a, b ) { - prefiltersOrTransports( prefilters, a, b ); - }, - - ajaxTransport: function( a, b ) { - return prefiltersOrTransports( transports, a, b ); - }, + ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), + ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { - // If options is not an object, - // we simulate pre-1.5 signature - if ( typeof options !== "object" ) { + // If url is an object, simulate pre-1.5 signature + if ( typeof url === "object" ) { options = url; url = undefined; } @@ -265,18 +348,24 @@ jQuery.extend({ var // Create the final options object s = jQuery.extend( true, {}, jQuery.ajaxSettings, options ), - // Callbacks contexts + // Callbacks context // We force the original context if it exists // or take it from jQuery.ajaxSettings otherwise // (plain objects used as context get extended) callbackContext = ( s.context = ( "context" in options ? options : jQuery.ajaxSettings ).context ) || s, - globalEventContext = callbackContext === s ? jQuery.event : jQuery( callbackContext ), + // Context for global events + // It's the callbackContext if one was provided in the options + // and if it's a DOM node + globalEventContext = callbackContext !== s && callbackContext.nodeType ? + jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery._Deferred(), // Status-dependent callbacks statusCode = s.statusCode || {}, + // ifModified key + ifModifiedKey, // Headers (they are sent all at once) requestHeaders = {}, // Response headers @@ -287,15 +376,13 @@ jQuery.extend({ // timeout handle timeoutTimer, // Cross-domain detection vars - loc = document.location, - protocol = loc.protocol || "http:", parts, - // The jXHR state + // The jqXHR state state = 0, // Loop variable i, // Fake xhr - jXHR = { + jqXHR = { readyState: 0, @@ -329,8 +416,9 @@ jQuery.extend({ // Cancel the request abort: function( statusText ) { + statusText = statusText || "abort"; if ( transport ) { - transport.abort( statusText || "abort" ); + transport.abort( statusText ); } done( 0, statusText ); return this; @@ -356,19 +444,19 @@ jQuery.extend({ } // Dereference transport for early garbage collection - // (no matter how long the jXHR object will be used) + // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState - jXHR.readyState = status ? 4 : 0; + jqXHR.readyState = status ? 4 : 0; var isSuccess, success, - error = ( statusText = statusText || "error" ), - response = responses ? ajaxHandleResponses( s, jXHR, responses ) : undefined, + error, + response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined, lastModified, etag; @@ -378,11 +466,11 @@ jQuery.extend({ // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { - if ( ( lastModified = jXHR.getResponseHeader( "Last-Modified" ) ) ) { - jQuery.lastModified[ s.url ] = lastModified; + if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) { + jQuery.lastModified[ ifModifiedKey ] = lastModified; } - if ( ( etag = jXHR.getResponseHeader( "Etag" ) ) ) { - jQuery.etag[ s.url ] = etag; + if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) { + jQuery.etag[ ifModifiedKey ] = etag; } } @@ -402,51 +490,61 @@ jQuery.extend({ } catch(e) { // We have a parsererror statusText = "parsererror"; - error = "" + e; + error = e; + } + } + } else { + // We extract error from statusText + // then normalize statusText and status for non-aborts + error = statusText; + if( status ) { + statusText = "error"; + if ( status < 0 ) { + status = 0; } } } // Set data for the fake xhr object - jXHR.status = status; - jXHR.statusText = statusText; + jqXHR.status = status; + jqXHR.statusText = statusText; // Success/Error if ( isSuccess ) { - deferred.resolveWith( callbackContext, [ success, statusText, jXHR ] ); + deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { - deferred.rejectWith( callbackContext, [ jXHR, statusText, error ] ); + deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks - jXHR.statusCode( statusCode ); + jqXHR.statusCode( statusCode ); statusCode = undefined; if ( s.global ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), - [ jXHR, s, isSuccess ? success : error ] ); + [ jqXHR, s, isSuccess ? success : error ] ); } // Complete - completeDeferred.resolveWith( callbackContext, [ jXHR, statusText ] ); + completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] ); if ( s.global ) { - globalEventContext.trigger( "ajaxComplete", [ jXHR, s] ); + globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] ); // Handle the global AJAX counter - if ( ! --jQuery.active ) { + if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds - deferred.promise( jXHR ); - jXHR.success = jXHR.done; - jXHR.error = jXHR.fail; - jXHR.complete = completeDeferred.done; + deferred.promise( jqXHR ); + jqXHR.success = jqXHR.done; + jqXHR.error = jqXHR.fail; + jqXHR.complete = completeDeferred.done; // Status-dependent callbacks - jXHR.statusCode = function( map ) { + jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { @@ -454,16 +552,17 @@ jQuery.extend({ statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { - tmp = map[ jXHR.status ]; - jXHR.then( tmp, tmp ); + tmp = map[ jqXHR.status ]; + jqXHR.then( tmp, tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) + // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available - s.url = ( "" + ( url || s.url ) ).replace( rhash, "" ); + s.url = ( "" + ( url || s.url ) ).replace( rhash, "" ).replace( rprotocol, ajaxLocation[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax ); @@ -471,12 +570,10 @@ jQuery.extend({ // Determine if a cross-domain request is in order if ( !s.crossDomain ) { parts = rurl.exec( s.url.toLowerCase() ); - s.crossDomain = !!( - parts && - ( parts[ 1 ] && parts[ 1 ] != protocol || - parts[ 2 ] != loc.hostname || - ( parts[ 3 ] || ( ( parts[ 1 ] || protocol ) === "http:" ? 80 : 443 ) ) != - ( loc.port || ( protocol === "http:" ? 80 : 443 ) ) ) + s.crossDomain = !!( parts && + ( parts[ 1 ] != ajaxLocation[ 1 ] || parts[ 2 ] != ajaxLocation[ 2 ] || + ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != + ( ajaxLocation[ 3 ] || ( ajaxLocation[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } @@ -486,7 +583,7 @@ jQuery.extend({ } // Apply prefilters - jQuery.ajaxPrefilter( s, options ); + inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // Uppercase the type s.type = s.type.toUpperCase(); @@ -507,6 +604,9 @@ jQuery.extend({ s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; } + // Get ifModifiedKey before adding the anti-cache parameter + ifModifiedKey = s.url; + // Add anti-cache in url if needed if ( s.cache === false ) { @@ -526,11 +626,12 @@ jQuery.extend({ // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { - if ( jQuery.lastModified[ s.url ] ) { - requestHeaders[ "if-modified-since" ] = jQuery.lastModified[ s.url ]; + ifModifiedKey = ifModifiedKey || s.url; + if ( jQuery.lastModified[ ifModifiedKey ] ) { + requestHeaders[ "if-modified-since" ] = jQuery.lastModified[ ifModifiedKey ]; } - if ( jQuery.etag[ s.url ] ) { - requestHeaders[ "if-none-match" ] = jQuery.etag[ s.url ]; + if ( jQuery.etag[ ifModifiedKey ] ) { + requestHeaders[ "if-none-match" ] = jQuery.etag[ ifModifiedKey ]; } } @@ -545,36 +646,36 @@ jQuery.extend({ } // Allow custom headers/mimetypes and early abort - if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jXHR, s ) === false || state === 2 ) ) { + if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already done( 0, "abort" ); // Return false - jXHR = false; + jqXHR = false; } else { // Install callbacks on deferreds - for ( i in { success:1, error:1, complete:1 } ) { - jXHR[ i ]( s[ i ] ); + for ( i in { success: 1, error: 1, complete: 1 } ) { + jqXHR[ i ]( s[ i ] ); } // Get transport - transport = jQuery.ajaxTransport( s, options ); + transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { - done( 0, "notransport" ); + done( -1, "No Transport" ); } else { // Set state as sending - state = jXHR.readyState = 1; + state = jqXHR.readyState = 1; // Send global event if ( s.global ) { - globalEventContext.trigger( "ajaxSend", [ jXHR, s ] ); + globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ - jXHR.abort( "timeout" ); + jqXHR.abort( "timeout" ); }, s.timeout ); } @@ -582,9 +683,8 @@ jQuery.extend({ transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done - if ( status === 1 ) { - done( 0, "error", "" + e ); - jXHR = false; + if ( status < 2 ) { + done( -1, e ); // Simply rethrow otherwise } else { jQuery.error( e ); @@ -592,7 +692,7 @@ jQuery.extend({ } } } - return jXHR; + return jqXHR; }, // Serialize an array of form elements or a set of @@ -611,7 +711,7 @@ jQuery.extend({ } // If an array was passed in, assume that it is an array of form elements. - if ( jQuery.isArray( a ) || a.jquery ) { + if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); @@ -630,6 +730,9 @@ jQuery.extend({ } }); +// Segment ajaxLocation into parts +ajaxLocation = rurl.exec( ajaxLocation.toLowerCase() ); + function buildParams( prefix, obj, traditional, add ) { if ( jQuery.isArray( obj ) && obj.length ) { // Serialize array item. @@ -658,9 +761,9 @@ function buildParams( prefix, obj, traditional, add ) { // Serialize object item. } else { - jQuery.each( obj, function( k, v ) { - buildParams( prefix + "[" + k + "]", v, traditional, add ); - }); + for ( var name in obj ) { + buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); + } } } else { @@ -682,102 +785,12 @@ jQuery.extend({ }); -// Base inspection function for prefilters and transports -function inspectPrefiltersOrTransports( structure, options, originalOptions, dataType, tested ) { - - dataType = dataType || options.dataTypes[ 0 ]; - tested = tested || {}; - - if ( !tested[ dataType ] ) { - - tested[ dataType ] = true; - - var list = structure[ dataType ], - i = 0, - length = list ? list.length : 0, - executeOnly = structure === prefilters, - selected; - - for(; ( executeOnly || !selected ) && i < length; i++ ) { - selected = list[ i ]( options, originalOptions ); - // If we got redirected to a different dataType, - // we add it and switch to the corresponding list - if ( typeof selected === "string" && selected !== dataType ) { - options.dataTypes.unshift( selected ); - selected = inspectPrefiltersOrTransports( - structure, options, originalOptions, selected, tested ); - // We always break in order not to continue - // to iterate in previous list - break; - } - } - // If we're only executing or nothing was selected - // we try the catchall dataType - if ( !tested[ "*" ] && ( executeOnly || ! selected ) ) { - selected = inspectPrefiltersOrTransports( - structure, options, originalOptions, "*" ,tested ); - } - // This will be ignored by ajaxPrefilter - // so it's safe to return no matter what - return selected; - } -} - -function addToPrefiltersOrTransports( structure, dataTypeExpression, functor ) { - - var dataTypes = dataTypeExpression.split( rspacesAjax ), - i = 0, - length = dataTypes.length, - dataType, - list, - placeBefore; - - // For each dataType in the dataTypeExpression - for(; i < length; i++ ) { - dataType = dataTypes[ i ]; - // We control if we're asked to add before - // any existing element - placeBefore = /^\+/.test( dataType ); - if ( placeBefore ) { - dataType = dataType.substr( 1 ); - } - list = structure[ dataType ] = structure[ dataType ] || []; - // then we add to the structure accordingly - list[ placeBefore ? "unshift" : "push" ]( functor ); - } -} - -// Base function for both ajaxPrefilter and ajaxTransport -function prefiltersOrTransports( structure, arg1, arg2, type /* internal */ ) { - - type = jQuery.type( arg1 ); - - if ( type === "object" ) { - // We have an options map so we have to inspect the structure - return inspectPrefiltersOrTransports( structure, arg1, arg2 ); - } else { - // We're requested to add to the structure - // Signature is ( dataTypeExpression, function ) - // with dataTypeExpression being optional and - // defaulting to auto ("*") - type = ( type === "function" ); - if ( type ) { - arg2 = arg1; - arg1 = undefined; - } - // We control that the second argument is really a function - if ( type || jQuery.isFunction( arg2 ) ) { - addToPrefiltersOrTransports( structure, arg1 || "*", arg2 ); - } - } -} - /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ -function ajaxHandleResponses( s, jXHR, responses ) { +function ajaxHandleResponses( s, jqXHR, responses ) { var contents = s.contents, dataTypes = s.dataTypes, @@ -790,7 +803,7 @@ function ajaxHandleResponses( s, jXHR, responses ) { // Fill responseXXX fields for( type in responseFields ) { if ( type in responses ) { - jXHR[ responseFields[type] ] = responses[ type ]; + jqXHR[ responseFields[type] ] = responses[ type ]; } } @@ -798,7 +811,7 @@ function ajaxHandleResponses( s, jXHR, responses ) { while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { - ct = jXHR.getResponseHeader( "content-type" ); + ct = jqXHR.getResponseHeader( "content-type" ); } } @@ -850,8 +863,9 @@ function ajaxConvert( s, response ) { } var dataTypes = s.dataTypes, - converters = s.converters, + converters = {}, i, + key, length = dataTypes.length, tmp, // Current and previous dataTypes @@ -861,13 +875,23 @@ function ajaxConvert( s, response ) { conversion, // Conversion function conv, - // Conversion functions (when text is used in-between) + // Conversion functions (transitive conversion) conv1, conv2; // For each dataType in the chain for( i = 1; i < length; i++ ) { + // Create converters map + // with lowercased keys + if ( i === 1 ) { + for( key in s.converters ) { + if( typeof key === "string" ) { + converters[ key.toLowerCase() ] = s.converters[ key ]; + } + } + } + // Get the dataTypes prev = current; current = dataTypes[ i ]; @@ -883,7 +907,7 @@ function ajaxConvert( s, response ) { conv = converters[ conversion ] || converters[ "* " + current ]; // If there is no direct converter, search transitively - if ( ! conv ) { + if ( !conv ) { conv2 = undefined; for( conv1 in converters ) { tmp = conv1.split( " " ); @@ -902,7 +926,7 @@ function ajaxConvert( s, response ) { } } // If we found no converter, dispatch an error - if ( ! ( conv || conv2 ) ) { + if ( !( conv || conv2 ) ) { jQuery.error( "No conversion from " + conversion.replace(" "," to ") ); } // If found converter is not an equivalence