7 rheaders = /^(.*?):\s*(.*?)\r?$/mg, // IE leaves an \r character at EOL
8 rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
9 // #7653, #8125, #8152: local protocol detection
10 rlocalProtocol = /(?:^file|^widget|\-extension):$/,
11 rnoContent = /^(?:GET|HEAD)$/,
14 rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
15 rselectTextarea = /^(?:select|textarea)/i,
17 rts = /([?&])_=[^&]*/,
18 rucHeaders = /(^|\-)([a-z])/g,
19 rucHeadersFunc = function( _, $1, $2 ) {
20 return $1 + $2.toUpperCase();
22 rurl = /^([\w\+\.\-]+:)\/\/([^\/?#:]*)(?::(\d+))?/,
24 // Keep a copy of the old load method
25 _load = jQuery.fn.load,
28 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
29 * 2) These are called:
30 * - BEFORE asking for a transport
31 * - AFTER param serialization (s.data is a string if s.processData is true)
32 * 3) key is the dataType
33 * 4) the catchall symbol "*" can be used
34 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
38 /* Transports bindings
39 * 1) key is the dataType
40 * 2) the catchall symbol "*" can be used
41 * 3) selection will start with transport dataType and THEN go to "*" if needed
48 // Document location segments
51 // #8138, IE may throw an exception when accessing
52 // a field from document.location if document.domain has been set
54 ajaxLocation = document.location.href;
56 // Use the href attribute of an A element
57 // since IE will modify it given document.location
58 ajaxLocation = document.createElement( "a" );
59 ajaxLocation.href = "";
60 ajaxLocation = ajaxLocation.href;
63 // Segment location into parts
64 ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() );
66 // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
67 function addToPrefiltersOrTransports( structure ) {
69 // dataTypeExpression is optional and defaults to "*"
70 return function( dataTypeExpression, func ) {
72 if ( typeof dataTypeExpression !== "string" ) {
73 func = dataTypeExpression;
74 dataTypeExpression = "*";
77 if ( jQuery.isFunction( func ) ) {
78 var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
80 length = dataTypes.length,
85 // For each dataType in the dataTypeExpression
86 for(; i < length; i++ ) {
87 dataType = dataTypes[ i ];
88 // We control if we're asked to add before
89 // any existing element
90 placeBefore = /^\+/.test( dataType );
92 dataType = dataType.substr( 1 ) || "*";
94 list = structure[ dataType ] = structure[ dataType ] || [];
95 // then we add to the structure accordingly
96 list[ placeBefore ? "unshift" : "push" ]( func );
102 //Base inspection function for prefilters and transports
103 function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
104 dataType /* internal */, inspected /* internal */ ) {
106 dataType = dataType || options.dataTypes[ 0 ];
107 inspected = inspected || {};
109 inspected[ dataType ] = true;
111 var list = structure[ dataType ],
113 length = list ? list.length : 0,
114 executeOnly = ( structure === prefilters ),
117 for(; i < length && ( executeOnly || !selection ); i++ ) {
118 selection = list[ i ]( options, originalOptions, jqXHR );
119 // If we got redirected to another dataType
120 // we try there if executing only and not done already
121 if ( typeof selection === "string" ) {
122 if ( !executeOnly || inspected[ selection ] ) {
123 selection = undefined;
125 options.dataTypes.unshift( selection );
126 selection = inspectPrefiltersOrTransports(
127 structure, options, originalOptions, jqXHR, selection, inspected );
131 // If we're only executing or nothing was selected
132 // we try the catchall dataType if not done already
133 if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
134 selection = inspectPrefiltersOrTransports(
135 structure, options, originalOptions, jqXHR, "*", inspected );
137 // unnecessary when only executing (prefilters)
138 // but it'll be ignored by the caller in that case
143 load: function( url, params, callback ) {
144 if ( typeof url !== "string" && _load ) {
145 return _load.apply( this, arguments );
147 // Don't do a request if no elements are being requested
148 } else if ( !this.length ) {
152 var off = url.indexOf( " " );
154 var selector = url.slice( off, url.length );
155 url = url.slice( 0, off );
158 // Default to a GET request
161 // If the second parameter was provided
163 // If it's a function
164 if ( jQuery.isFunction( params ) ) {
165 // We assume that it's the callback
169 // Otherwise, build a param string
170 } else if ( typeof params === "object" ) {
171 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
178 // Request the remote document
184 // Complete callback (responseText is used internally)
185 complete: function( jqXHR, status, responseText ) {
186 // Store the response as specified by the jqXHR object
187 responseText = jqXHR.responseText;
188 // If successful, inject the HTML into all the matched elements
189 if ( jqXHR.isResolved() ) {
190 // #4825: Get the actual response in case
191 // a dataFilter is present in ajaxSettings
192 jqXHR.done(function( r ) {
195 // See if a selector was specified
196 self.html( selector ?
197 // Create a dummy div to hold the results
199 // inject the contents of the document in, removing the scripts
200 // to avoid any 'Permission Denied' errors in IE
201 .append(responseText.replace(rscript, ""))
203 // Locate the specified elements
206 // If not, just inject the full result
211 self.each( callback, [ responseText, status, jqXHR ] );
219 serialize: function() {
220 return jQuery.param( this.serializeArray() );
223 serializeArray: function() {
224 return this.map(function(){
225 return this.elements ? jQuery.makeArray( this.elements ) : this;
228 return this.name && !this.disabled &&
229 ( this.checked || rselectTextarea.test( this.nodeName ) ||
230 rinput.test( this.type ) );
232 .map(function( i, elem ){
233 var val = jQuery( this ).val();
237 jQuery.isArray( val ) ?
238 jQuery.map( val, function( val, i ){
239 return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
241 { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
246 // Attach a bunch of functions for handling common AJAX events
247 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
248 jQuery.fn[ o ] = function( f ){
249 return this.bind( o, f );
253 jQuery.each( [ "get", "post" ], function( i, method ) {
254 jQuery[ method ] = function( url, data, callback, type ) {
255 // shift arguments if data argument was omitted
256 if ( jQuery.isFunction( data ) ) {
257 type = type || callback;
274 getScript: function( url, callback ) {
275 return jQuery.get( url, null, callback, "script" );
278 getJSON: function( url, data, callback ) {
279 return jQuery.get( url, data, callback, "json" );
282 ajaxSetup: function( settings ) {
283 jQuery.extend( true, jQuery.ajaxSettings, settings );
284 if ( settings.context ) {
285 jQuery.ajaxSettings.context = settings.context;
291 isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
294 contentType: "application/x-www-form-urlencoded",
310 xml: "application/xml, text/xml",
313 json: "application/json, text/javascript",
328 // List of data converters
329 // 1) key format is "source_type destination_type" (a single space in-between)
330 // 2) the catchall symbol "*" can be used for source_type
333 // Convert anything to text
334 "* text": window.String,
336 // Text to html (true = no transformation)
339 // Evaluate text as a json expression
340 "text json": jQuery.parseJSON,
343 "text xml": jQuery.parseXML
347 ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
348 ajaxTransport: addToPrefiltersOrTransports( transports ),
351 ajax: function( url, options ) {
353 // If url is an object, simulate pre-1.5 signature
354 if ( typeof url === "object" ) {
359 // Force options to be an object
360 options = options || {};
362 var // Create the final options object
363 s = jQuery.extend( true, {}, jQuery.ajaxSettings, options ),
365 // We force the original context if it exists
366 // or take it from jQuery.ajaxSettings otherwise
367 // (plain objects used as context get extended)
369 ( s.context = ( "context" in options ? options : jQuery.ajaxSettings ).context ) || s,
370 // Context for global events
371 // It's the callbackContext if one was provided in the options
372 // and if it's a DOM node or a jQuery collection
373 globalEventContext = callbackContext !== s &&
374 ( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
375 jQuery( callbackContext ) : jQuery.event,
377 deferred = jQuery.Deferred(),
378 completeDeferred = jQuery._Deferred(),
379 // Status-dependent callbacks
380 statusCode = s.statusCode || {},
383 // Headers (they are sent all at once)
386 responseHeadersString,
392 // Cross-domain detection vars
396 // To know if global events are to be dispatched
406 setRequestHeader: function( name, value ) {
408 requestHeaders[ name.toLowerCase().replace( rucHeaders, rucHeadersFunc ) ] = value;
414 getAllResponseHeaders: function() {
415 return state === 2 ? responseHeadersString : null;
418 // Builds headers hashtable if needed
419 getResponseHeader: function( key ) {
422 if ( !responseHeaders ) {
423 responseHeaders = {};
424 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
425 responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
428 match = responseHeaders[ key.toLowerCase() ];
430 return match || null;
433 // Overrides response content-type header
434 overrideMimeType: function( type ) {
441 // Cancel the request
442 abort: function( statusText ) {
443 statusText = statusText || "abort";
445 transport.abort( statusText );
447 done( 0, statusText );
452 // Callback for when everything is done
453 // It is defined here because jslint complains if it is declared
454 // at the end of the function (which would be more logical and readable)
455 function done( status, statusText, responses, headers ) {
462 // State is "done" now
465 // Clear timeout if it exists
466 if ( timeoutTimer ) {
467 clearTimeout( timeoutTimer );
470 // Dereference transport for early garbage collection
471 // (no matter how long the jqXHR object will be used)
472 transport = undefined;
474 // Cache response headers
475 responseHeadersString = headers || "";
478 jqXHR.readyState = status ? 4 : 0;
483 response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
487 // If successful, handle type chaining
488 if ( status >= 200 && status < 300 || status === 304 ) {
490 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
491 if ( s.ifModified ) {
493 if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
494 jQuery.lastModified[ ifModifiedKey ] = lastModified;
496 if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
497 jQuery.etag[ ifModifiedKey ] = etag;
502 if ( status === 304 ) {
504 statusText = "notmodified";
511 success = ajaxConvert( s, response );
512 statusText = "success";
515 // We have a parsererror
516 statusText = "parsererror";
521 // We extract error from statusText
522 // then normalize statusText and status for non-aborts
524 if( !statusText || status ) {
525 statusText = "error";
532 // Set data for the fake xhr object
533 jqXHR.status = status;
534 jqXHR.statusText = statusText;
538 deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
540 deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
543 // Status-dependent callbacks
544 jqXHR.statusCode( statusCode );
545 statusCode = undefined;
548 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
549 [ jqXHR, s, isSuccess ? success : error ] );
553 completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );
556 globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] );
557 // Handle the global AJAX counter
558 if ( !( --jQuery.active ) ) {
559 jQuery.event.trigger( "ajaxStop" );
565 deferred.promise( jqXHR );
566 jqXHR.success = jqXHR.done;
567 jqXHR.error = jqXHR.fail;
568 jqXHR.complete = completeDeferred.done;
570 // Status-dependent callbacks
571 jqXHR.statusCode = function( map ) {
576 statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
579 tmp = map[ jqXHR.status ];
580 jqXHR.then( tmp, tmp );
586 // Remove hash character (#7531: and string promotion)
587 // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
588 // We also use the url parameter if available
589 s.url = ( "" + ( url || s.url ) ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
591 // Extract dataTypes list
592 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
594 // Determine if a cross-domain request is in order
595 if ( !s.crossDomain ) {
596 parts = rurl.exec( s.url.toLowerCase() );
597 s.crossDomain = !!( parts &&
598 ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
599 ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
600 ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
604 // Convert data if not already a string
605 if ( s.data && s.processData && typeof s.data !== "string" ) {
606 s.data = jQuery.param( s.data, s.traditional );
610 inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
612 // If request was aborted inside a prefiler, stop there
617 // We can fire global events as of now if asked to
618 fireGlobals = s.global;
620 // Uppercase the type
621 s.type = s.type.toUpperCase();
623 // Determine if request has content
624 s.hasContent = !rnoContent.test( s.type );
626 // Watch for a new set of requests
627 if ( fireGlobals && jQuery.active++ === 0 ) {
628 jQuery.event.trigger( "ajaxStart" );
631 // More options handling for requests with no content
632 if ( !s.hasContent ) {
634 // If data is available, append data to url
636 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
639 // Get ifModifiedKey before adding the anti-cache parameter
640 ifModifiedKey = s.url;
642 // Add anti-cache in url if needed
643 if ( s.cache === false ) {
645 var ts = jQuery.now(),
646 // try replacing _= if it is there
647 ret = s.url.replace( rts, "$1_=" + ts );
649 // if nothing was replaced, add timestamp to the end
650 s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
654 // Set the correct header, if data is being sent
655 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
656 requestHeaders[ "Content-Type" ] = s.contentType;
659 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
660 if ( s.ifModified ) {
661 ifModifiedKey = ifModifiedKey || s.url;
662 if ( jQuery.lastModified[ ifModifiedKey ] ) {
663 requestHeaders[ "If-Modified-Since" ] = jQuery.lastModified[ ifModifiedKey ];
665 if ( jQuery.etag[ ifModifiedKey ] ) {
666 requestHeaders[ "If-None-Match" ] = jQuery.etag[ ifModifiedKey ];
670 // Set the Accepts header for the server, depending on the dataType
671 requestHeaders.Accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
672 s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
675 // Check for headers option
676 for ( i in s.headers ) {
677 jqXHR.setRequestHeader( i, s.headers[ i ] );
680 // Allow custom headers/mimetypes and early abort
681 if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
682 // Abort if not done already
688 // Install callbacks on deferreds
689 for ( i in { success: 1, error: 1, complete: 1 } ) {
690 jqXHR[ i ]( s[ i ] );
694 transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
696 // If no transport, we auto-abort
698 done( -1, "No Transport" );
700 jqXHR.readyState = 1;
703 globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
706 if ( s.async && s.timeout > 0 ) {
707 timeoutTimer = setTimeout( function(){
708 jqXHR.abort( "timeout" );
714 transport.send( requestHeaders, done );
716 // Propagate exception as error if not done
719 // Simply rethrow otherwise
729 // Serialize an array of form elements or a set of
730 // key/values into a query string
731 param: function( a, traditional ) {
733 add = function( key, value ) {
734 // If value is a function, invoke it and return its value
735 value = jQuery.isFunction( value ) ? value() : value;
736 s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
739 // Set traditional to true for jQuery <= 1.3.2 behavior.
740 if ( traditional === undefined ) {
741 traditional = jQuery.ajaxSettings.traditional;
744 // If an array was passed in, assume that it is an array of form elements.
745 if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
746 // Serialize the form elements
747 jQuery.each( a, function() {
748 add( this.name, this.value );
752 // If traditional, encode the "old" way (the way 1.3.2 or older
753 // did it), otherwise encode params recursively.
754 for ( var prefix in a ) {
755 buildParams( prefix, a[ prefix ], traditional, add );
759 // Return the resulting serialization
760 return s.join( "&" ).replace( r20, "+" );
764 function buildParams( prefix, obj, traditional, add ) {
765 if ( jQuery.isArray( obj ) && obj.length ) {
766 // Serialize array item.
767 jQuery.each( obj, function( i, v ) {
768 if ( traditional || rbracket.test( prefix ) ) {
769 // Treat each array item as a scalar.
773 // If array item is non-scalar (array or object), encode its
774 // numeric index to resolve deserialization ambiguity issues.
775 // Note that rack (as of 1.0.0) can't currently deserialize
776 // nested arrays properly, and attempting to do so may cause
777 // a server error. Possible fixes are to modify rack's
778 // deserialization algorithm or to provide an option or flag
779 // to force array serialization to be shallow.
780 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
784 } else if ( !traditional && obj != null && typeof obj === "object" ) {
785 // If we see an array here, it is empty and should be treated as an empty
787 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
790 // Serialize object item.
792 for ( var name in obj ) {
793 buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
798 // Serialize scalar item.
803 // This is still on the jQuery object... for now
804 // Want to move this to jQuery.ajax some day
807 // Counter for holding the number of active queries
810 // Last-Modified header cache for next request
816 /* Handles responses to an ajax request:
817 * - sets all responseXXX fields accordingly
818 * - finds the right dataType (mediates between content-type and expected dataType)
819 * - returns the corresponding response
821 function ajaxHandleResponses( s, jqXHR, responses ) {
823 var contents = s.contents,
824 dataTypes = s.dataTypes,
825 responseFields = s.responseFields,
831 // Fill responseXXX fields
832 for( type in responseFields ) {
833 if ( type in responses ) {
834 jqXHR[ responseFields[type] ] = responses[ type ];
838 // Remove auto dataType and get content-type in the process
839 while( dataTypes[ 0 ] === "*" ) {
841 if ( ct === undefined ) {
842 ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
846 // Check if we're dealing with a known content-type
848 for ( type in contents ) {
849 if ( contents[ type ] && contents[ type ].test( ct ) ) {
850 dataTypes.unshift( type );
856 // Check to see if we have a response for the expected dataType
857 if ( dataTypes[ 0 ] in responses ) {
858 finalDataType = dataTypes[ 0 ];
860 // Try convertible dataTypes
861 for ( type in responses ) {
862 if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
863 finalDataType = type;
866 if ( !firstDataType ) {
867 firstDataType = type;
870 // Or just use first one
871 finalDataType = finalDataType || firstDataType;
874 // If we found a dataType
875 // We add the dataType to the list if needed
876 // and return the corresponding response
877 if ( finalDataType ) {
878 if ( finalDataType !== dataTypes[ 0 ] ) {
879 dataTypes.unshift( finalDataType );
881 return responses[ finalDataType ];
885 // Chain conversions given the request and the original response
886 function ajaxConvert( s, response ) {
888 // Apply the dataFilter if provided
889 if ( s.dataFilter ) {
890 response = s.dataFilter( response, s.dataType );
893 var dataTypes = s.dataTypes,
897 length = dataTypes.length,
899 // Current and previous dataTypes
900 current = dataTypes[ 0 ],
902 // Conversion expression
904 // Conversion function
906 // Conversion functions (transitive conversion)
910 // For each dataType in the chain
911 for( i = 1; i < length; i++ ) {
913 // Create converters map
914 // with lowercased keys
916 for( key in s.converters ) {
917 if( typeof key === "string" ) {
918 converters[ key.toLowerCase() ] = s.converters[ key ];
925 current = dataTypes[ i ];
927 // If current is auto dataType, update it to prev
928 if( current === "*" ) {
930 // If no auto and dataTypes are actually different
931 } else if ( prev !== "*" && prev !== current ) {
934 conversion = prev + " " + current;
935 conv = converters[ conversion ] || converters[ "* " + current ];
937 // If there is no direct converter, search transitively
940 for( conv1 in converters ) {
941 tmp = conv1.split( " " );
942 if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
943 conv2 = converters[ tmp[1] + " " + current ];
945 conv1 = converters[ conv1 ];
946 if ( conv1 === true ) {
948 } else if ( conv2 === true ) {
956 // If we found no converter, dispatch an error
957 if ( !( conv || conv2 ) ) {
958 jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
960 // If found converter is not an equivalence
961 if ( conv !== true ) {
962 // Convert with 1 or 2 converters accordingly
963 response = conv ? conv( response ) : conv2( conv1(response) );