5 rheaders = /^(.*?):\s*(.*?)\r?$/mg, // IE leaves an \r character at EOL
6 rnoContent = /^(?:GET|HEAD)$/,
8 rurl = /^(\w+:)?\/\/([^\/?#]+)/,
10 sliceFunc = Array.prototype.slice,
12 isFunction = jQuery.isFunction;
14 // Creates a jQuery xhr object
15 jQuery.xhr = function( _native ) {
18 return jQuery.ajaxSettings.xhr();
21 function reset( force ) {
23 // We only need to reset if we went through the init phase
24 // (with the exception of object creation)
25 if ( force || internal ) {
27 // Reset callbacks lists
28 deferred = jQuery.deferred();
29 completeDeferred = jQuery._deferred();
31 xhr.success = xhr.then = deferred.then;
32 xhr.error = xhr.fail = deferred.fail;
33 xhr.complete = completeDeferred.then;
35 // Reset private variables
37 responseHeadersString = responseHeaders = internal = done = timeoutTimer = s = undefined;
43 // Remove responseX fields
44 for ( var name in xhr ) {
45 if ( /^response/.test(name) ) {
54 var // Options extraction
56 // Remove hash character (#7531: first for string promotion)
57 url = s.url = ( "" + s.url ).replace( rhash , "" ),
60 type = s.type = s.type.toUpperCase(),
62 // Determine if request has content
63 hasContent = s.hasContent = ! rnoContent.test( type ),
65 // Extract dataTypes list
66 dataType = s.dataType,
67 dataTypes = s.dataTypes = dataType ? jQuery.trim(dataType).toLowerCase().split(/\s+/) : ["*"],
69 // Determine if a cross-domain request is in order
70 parts = rurl.exec( url.toLowerCase() ),
72 crossDomain = s.crossDomain = !!( parts && ( parts[1] && parts[1] != loc.protocol || parts[2] != loc.host ) ),
74 // Get other options locally
76 originalContentType = s.contentType,
77 prefilters = s.prefilters,
85 // Convert data if not already a string
86 if ( data && s.processData && typeof data != "string" ) {
87 data = s.data = jQuery.param( data , s.traditional );
90 // Apply option prefilters
91 for ( i = 0; i < prefilters.length; i++ ) {
96 internal = selectTransport( s );
98 // Re-actualize url & data
102 // If internal was found
105 // Get transportDataType
106 transportDataType = dataTypes[0];
108 // More options handling for requests with no content
109 if ( ! hasContent ) {
111 // If data is available, append data to url
113 url += (rquery_xhr.test(url) ? "&" : "?") + data;
116 // Add anti-cache in url if needed
117 if ( s.cache === false ) {
119 var ts = jQuery.now(),
120 // try replacing _= if it is there
121 ret = url.replace(rts, "$1_=" + ts );
123 // if nothing was replaced, add timestamp to the end
124 url = ret + ((ret == url) ? (rquery_xhr.test(url) ? "&" : "?") + "_=" + ts : "");
130 // Set the correct header, if data is being sent
131 if ( ( data && hasContent ) || originalContentType ) {
132 requestHeaders["content-type"] = s.contentType;
135 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
136 if ( s.ifModified ) {
137 if ( jQuery_lastModified[url] ) {
138 requestHeaders["if-modified-since"] = jQuery_lastModified[url];
140 if ( jQuery_etag[url] ) {
141 requestHeaders["if-none-match"] = jQuery_etag[url];
145 // Set the Accepts header for the server, depending on the dataType
146 requestHeaders.accept = transportDataType && accepts[ transportDataType ] ?
147 accepts[ transportDataType ] + ( transportDataType !== "*" ? ", */*; q=0.01" : "" ) :
150 // Check for headers option
151 for ( i in headers ) {
152 requestHeaders[ i.toLowerCase() ] = headers[ i ];
156 callbackContext = s.context || s;
157 globalEventContext = s.context ? jQuery(s.context) : jQuery.event;
159 for ( i in { success:1, error:1, complete:1 } ) {
163 // Watch for a new set of requests
164 if ( s.global && jQuery.active++ === 0 ) {
165 jQuery.event.trigger( "ajaxStart" );
171 function whenDone(status, statusText, response, headers) {
179 // Cache response headers
180 responseHeadersString = headers || "";
182 // Clear timeout if it exists
183 if ( timeoutTimer ) {
184 clearTimeout(timeoutTimer);
189 // and ifModified status
190 ifModified = s.ifModified,
199 // If not timeout, force a jQuery-compliant status text
200 if ( statusText != "timeout" ) {
201 statusText = ( status >= 200 && status < 300 ) ?
203 ( status === 304 ? "notmodified" : "error" );
206 // If successful, handle type chaining
207 if ( statusText === "success" || statusText === "notmodified" ) {
209 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
211 var lastModified = xhr.getResponseHeader("Last-Modified"),
212 etag = xhr.getResponseHeader("Etag");
215 jQuery_lastModified[url] = lastModified;
218 jQuery_etag[url] = etag;
222 if ( ifModified && statusText === "notmodified" ) {
228 // Chain data conversions and determine the final value
229 // (if an exception is thrown in the process, it'll be notified as an error)
232 function checkData(data) {
233 if ( data !== undefined ) {
234 var testFunction = s.dataCheckers[srcDataType];
235 if ( isFunction( testFunction ) ) {
241 function convertData (data) {
242 var conversionFunction = dataConverters[srcDataType+" => "+destDataType] ||
243 dataConverters["* => "+destDataType],
244 noFunction = ! isFunction( conversionFunction );
246 if ( srcDataType != "text" && destDataType != "text" ) {
247 // We try to put text inbetween
248 var first = dataConverters[srcDataType+" => text"] ||
249 dataConverters["* => text"],
250 second = dataConverters["text => "+destDataType] ||
251 dataConverters["* => "+destDataType],
252 areFunctions = isFunction( first ) && isFunction( second );
253 if ( areFunctions ) {
254 conversionFunction = function (data) {
255 return second( first ( data ) );
258 noFunction = ! areFunctions;
261 jQuery.error( "no data converter between " + srcDataType + " and " + destDataType );
265 return conversionFunction(data);
268 var dataTypes = s.dataTypes,
272 dataConverters = s.dataConverters,
275 responseTypes = s.xhrResponseFields;
277 for ( i = 0, length = dataTypes.length ; i < length ; i++ ) {
279 destDataType = dataTypes[i];
281 if ( !srcDataType ) { // First time
284 srcDataType = destDataType;
288 if ( isFunction( s.dataFilter ) ) {
289 data = s.dataFilter(data, s.dataType);
294 } else { // Subsequent times
297 // JULIAN: for reasons unknown to me === doesn't work here
298 if (destDataType == "*") {
300 destDataType = srcDataType;
302 } else if ( srcDataType != destDataType ) {
305 data = convertData(data);
307 srcDataType = destDataType;
314 // Copy response into the xhr if it hasn't been already
315 var responseDataType,
316 responseType = responseTypes[srcDataType];
318 if ( responseType ) {
320 responseDataType = srcDataType;
324 responseType = responseTypes[ responseDataType = "text" ];
328 if ( responseType !== 1 ) {
329 xhr[ "response" + responseType ] = data;
330 responseTypes[ responseType ] = 1;
335 // We have a real success
341 statusText = "parsererror";
347 } else { // if not success, mark it as an error
349 error = error || statusText;
353 // Set data for the fake xhr object
355 xhr.statusText = statusText;
357 // Keep local copies of vars in case callbacks re-use the xhr
359 _deferred = deferred,
360 _completeDeferred = completeDeferred,
361 _callbackContext = callbackContext,
362 _globalEventContext = globalEventContext;
365 // Set state if the xhr hasn't been re-used
366 function _setState( value ) {
367 if ( xhr.readyState && s === _s ) {
373 if ( status && s.async ) {
383 _deferred.fire( _callbackContext , [ success , statusText , xhr ] );
385 _deferred.fireReject( _callbackContext , [ xhr , statusText , error ] );
389 _globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ) , [ xhr , _s , isSuccess ? success : error ] );
393 _completeDeferred.fire( _callbackContext, [ xhr , statusText ] );
396 _globalEventContext.trigger( "ajaxComplete", [xhr, _s] );
397 // Handle the global AJAX counter
398 if ( ! --jQuery.active ) {
399 jQuery.event.trigger( "ajaxStop" );
404 // Ready state control
405 function checkState( expected , test ) {
406 if ( expected !== true && ( expected === false || test === false || xhr.readyState !== expected ) ) {
407 jQuery.error("INVALID_STATE_ERR");
411 // Ready state change
412 function setState( value ) {
413 xhr.readyState = value;
414 if ( isFunction( xhr.onreadystatechange ) ) {
415 xhr.onreadystatechange();
420 jQuery_lastModified = jQuery.lastModified,
421 jQuery_etag = jQuery.etag,
429 // Headers (they are sent all at once)
432 responseHeadersString,
448 onreadystatechange: null,
451 open: function(type, url, async, username, password) {
470 send: function(data, moreOptions) {
472 checkState(1 , !sendFlag);
476 s = jQuery.extend( true,
480 moreOptions || ( moreOptions === false ? { global: false } : {} ) );
483 // We force the original context
484 // (plain objects used as context get extended)
485 s.context = moreOptions.context;
490 // If not internal, abort
492 done( 0 , "transport not found" );
496 // Allow custom headers/mimetypes and early abort
497 if ( s.beforeSend ) {
501 if ( s.beforeSend.call(callbackContext, xhr, s) === false || ! xhr.readyState || _s !== s ) {
504 if ( xhr.readyState && _s === s ) {
508 // Handle the global AJAX counter
509 if ( _s.global && ! --jQuery.active ) {
510 jQuery.event.trigger( "ajaxStop" );
521 globalEventContext.trigger("ajaxSend", [xhr, s]);
525 if ( s.async && s.timeout > 0 ) {
526 timeoutTimer = setTimeout(function(){
527 xhr.abort("timeout");
537 internal.send(requestHeaders, done);
544 done(0, "error", "" + e);
557 setRequestHeader: function(name,value) {
558 checkState(1, !sendFlag);
559 requestHeaders[ name.toLowerCase() ] = value;
564 getAllResponseHeaders: function() {
565 return xhr.readyState <= 1 ? "" : responseHeadersString;
568 // Builds headers hashtable if needed
569 getResponseHeader: function( key ) {
571 if ( xhr.readyState <= 1 ) {
577 if ( responseHeaders === undefined ) {
579 responseHeaders = {};
581 if ( typeof responseHeadersString === "string" ) {
585 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
586 responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
590 return responseHeaders[ key.toLowerCase() ];
593 // Cancel the request
594 abort: function(statusText) {
596 internal.abort( statusText || "abort" );
602 // Init data (so that we can bind callbacks early
605 // Return the xhr emulation
609 jQuery.extend(jQuery.xhr, {
612 prefilter: function (functor) {
613 if ( isFunction(functor) ) {
614 jQuery.ajaxSettings.prefilters.push( functor );
619 // Bind a transport to one or more dataTypes
620 bindTransport: function () {
622 var args = arguments,
625 length = args.length,
632 transports = jQuery.ajaxSettings.transports;
636 if ( ! isFunction( args[ 0 ] ) ) {
638 dataTypes = args[ 0 ].toLowerCase().split(/\s+/);
643 if ( dataTypes.length && start < length ) {
645 for ( i = start; i < length; i++ ) {
647 if ( isFunction(functor) ) {
648 functors.push( functor );
652 if ( functors.length ) {
654 jQuery.each ( dataTypes, function( _ , dataType ) {
656 first = /^\+/.test( dataType );
659 dataType = dataType.substr(1);
662 if ( dataType !== "" ) {
664 append = Array.prototype[ first ? "unshift" : "push" ];
666 list = transports[ dataType ];
668 jQuery.each ( functors, function( _ , functor ) {
672 list = transports[ dataType ] = [ functor ];
676 append.call( list , functor );
692 // Select a transport given options
693 function selectTransport( s ) {
695 var dataTypes = s.dataTypes,
704 function initSearch( dataType ) {
706 flag = transportDataType !== dataType && ! checked[ dataType ];
710 checked[ dataType ] = 1;
711 transportDataType = dataType;
712 transportsList = s.transports[ dataType ];
714 length = transportsList ? transportsList.length : 0 ;
720 initSearch( dataTypes[ 0 ] );
722 for ( i = 0 ; ! transport && i <= length ; i++ ) {
724 if ( i === length ) {
730 transport = transportsList[ i ]( s , determineDataType );
732 // If we got redirected to another dataType
733 // Search there (if not in progress or already tried)
734 if ( typeof( transport ) === "string" &&
735 initSearch( transport ) ) {
737 dataTypes.unshift( transport );
746 // Utility function that handles dataType when response is received
747 // (for those transports that can give text or xml responses)
748 function determineDataType( s , ct , text , xml ) {
750 var autoDataType = s.autoDataType,
753 dataTypes = s.dataTypes,
754 transportDataType = dataTypes[0],
757 // Auto (xml, json, script or text determined given headers)
758 if ( transportDataType === "*" ) {
760 for ( type in autoDataType ) {
761 if ( ( regexp = autoDataType[ type ] ) && regexp.test( ct ) ) {
762 transportDataType = dataTypes[0] = type;
768 // xml and parsed as such
769 if ( transportDataType === "xml" &&
771 xml.documentElement /* #4958 */ ) {
775 // Text response was provided
780 // If it's not really text, defer to dataConverters
781 if ( transportDataType !== "text" ) {
782 dataTypes.unshift( "text" );