7 rheaders = /^(.*?):[ \t]*([^\r\n]*)\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 = /^(?:about|app|app\-storage|.+\-extension|file|widget):$/,
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, undefined, callback, "script" );
278 getJSON: function( url, data, callback ) {
279 return jQuery.get( url, data, callback, "json" );
282 // Creates a full fledged settings object into target
283 // with both ajaxSettings and settings fields.
284 // If target is omitted, writes into ajaxSettings.
285 ajaxSetup: function ( target, settings ) {
287 // Only one parameter, we extend ajaxSettings
289 target = jQuery.extend( true, jQuery.ajaxSettings, settings );
291 // target was provided, we extend into it
292 jQuery.extend( true, target, jQuery.ajaxSettings, settings );
294 // Flatten fields we don't want deep extended
295 for( var field in { context: 1, url: 1 } ) {
296 if ( field in settings ) {
297 target[ field ] = settings[ field ];
298 } else if( field in jQuery.ajaxSettings ) {
299 target[ field ] = jQuery.ajaxSettings[ field ];
307 isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
310 contentType: "application/x-www-form-urlencoded",
326 xml: "application/xml, text/xml",
329 json: "application/json, text/javascript",
344 // List of data converters
345 // 1) key format is "source_type destination_type" (a single space in-between)
346 // 2) the catchall symbol "*" can be used for source_type
349 // Convert anything to text
350 "* text": window.String,
352 // Text to html (true = no transformation)
355 // Evaluate text as a json expression
356 "text json": jQuery.parseJSON,
359 "text xml": jQuery.parseXML
363 ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
364 ajaxTransport: addToPrefiltersOrTransports( transports ),
367 ajax: function( url, options ) {
369 // If url is an object, simulate pre-1.5 signature
370 if ( typeof url === "object" ) {
375 // Force options to be an object
376 options = options || {};
378 var // Create the final options object
379 s = jQuery.ajaxSetup( {}, options ),
381 callbackContext = s.context || s,
382 // Context for global events
383 // It's the callbackContext if one was provided in the options
384 // and if it's a DOM node or a jQuery collection
385 globalEventContext = callbackContext !== s &&
386 ( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
387 jQuery( callbackContext ) : jQuery.event,
389 deferred = jQuery.Deferred(),
390 completeDeferred = jQuery._Deferred(),
391 // Status-dependent callbacks
392 statusCode = s.statusCode || {},
395 // Headers (they are sent all at once)
398 responseHeadersString,
404 // Cross-domain detection vars
408 // To know if global events are to be dispatched
418 setRequestHeader: function( name, value ) {
420 requestHeaders[ name.toLowerCase().replace( rucHeaders, rucHeadersFunc ) ] = value;
426 getAllResponseHeaders: function() {
427 return state === 2 ? responseHeadersString : null;
430 // Builds headers hashtable if needed
431 getResponseHeader: function( key ) {
434 if ( !responseHeaders ) {
435 responseHeaders = {};
436 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
437 responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
440 match = responseHeaders[ key.toLowerCase() ];
442 return match === undefined ? null : match;
445 // Overrides response content-type header
446 overrideMimeType: function( type ) {
453 // Cancel the request
454 abort: function( statusText ) {
455 statusText = statusText || "abort";
457 transport.abort( statusText );
459 done( 0, statusText );
464 // Callback for when everything is done
465 // It is defined here because jslint complains if it is declared
466 // at the end of the function (which would be more logical and readable)
467 function done( status, statusText, responses, headers ) {
474 // State is "done" now
477 // Clear timeout if it exists
478 if ( timeoutTimer ) {
479 clearTimeout( timeoutTimer );
482 // Dereference transport for early garbage collection
483 // (no matter how long the jqXHR object will be used)
484 transport = undefined;
486 // Cache response headers
487 responseHeadersString = headers || "";
490 jqXHR.readyState = status ? 4 : 0;
495 response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
499 // If successful, handle type chaining
500 if ( status >= 200 && status < 300 || status === 304 ) {
502 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
503 if ( s.ifModified ) {
505 if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
506 jQuery.lastModified[ ifModifiedKey ] = lastModified;
508 if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
509 jQuery.etag[ ifModifiedKey ] = etag;
514 if ( status === 304 ) {
516 statusText = "notmodified";
523 success = ajaxConvert( s, response );
524 statusText = "success";
527 // We have a parsererror
528 statusText = "parsererror";
533 // We extract error from statusText
534 // then normalize statusText and status for non-aborts
536 if( !statusText || status ) {
537 statusText = "error";
544 // Set data for the fake xhr object
545 jqXHR.status = status;
546 jqXHR.statusText = statusText;
550 deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
552 deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
555 // Status-dependent callbacks
556 jqXHR.statusCode( statusCode );
557 statusCode = undefined;
560 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
561 [ jqXHR, s, isSuccess ? success : error ] );
565 completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );
568 globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] );
569 // Handle the global AJAX counter
570 if ( !( --jQuery.active ) ) {
571 jQuery.event.trigger( "ajaxStop" );
577 deferred.promise( jqXHR );
578 jqXHR.success = jqXHR.done;
579 jqXHR.error = jqXHR.fail;
580 jqXHR.complete = completeDeferred.done;
582 // Status-dependent callbacks
583 jqXHR.statusCode = function( map ) {
588 statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
591 tmp = map[ jqXHR.status ];
592 jqXHR.then( tmp, tmp );
598 // Remove hash character (#7531: and string promotion)
599 // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
600 // We also use the url parameter if available
601 s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
603 // Extract dataTypes list
604 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
606 // Determine if a cross-domain request is in order
607 if ( !s.crossDomain ) {
608 parts = rurl.exec( s.url.toLowerCase() );
609 s.crossDomain = !!( parts &&
610 ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
611 ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
612 ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
616 // Convert data if not already a string
617 if ( s.data && s.processData && typeof s.data !== "string" ) {
618 s.data = jQuery.param( s.data, s.traditional );
622 inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
624 // If request was aborted inside a prefiler, stop there
629 // We can fire global events as of now if asked to
630 fireGlobals = s.global;
632 // Uppercase the type
633 s.type = s.type.toUpperCase();
635 // Determine if request has content
636 s.hasContent = !rnoContent.test( s.type );
638 // Watch for a new set of requests
639 if ( fireGlobals && jQuery.active++ === 0 ) {
640 jQuery.event.trigger( "ajaxStart" );
643 // More options handling for requests with no content
644 if ( !s.hasContent ) {
646 // If data is available, append data to url
648 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
651 // Get ifModifiedKey before adding the anti-cache parameter
652 ifModifiedKey = s.url;
654 // Add anti-cache in url if needed
655 if ( s.cache === false ) {
657 var ts = jQuery.now(),
658 // try replacing _= if it is there
659 ret = s.url.replace( rts, "$1_=" + ts );
661 // if nothing was replaced, add timestamp to the end
662 s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
666 // Set the correct header, if data is being sent
667 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
668 requestHeaders[ "Content-Type" ] = s.contentType;
671 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
672 if ( s.ifModified ) {
673 ifModifiedKey = ifModifiedKey || s.url;
674 if ( jQuery.lastModified[ ifModifiedKey ] ) {
675 requestHeaders[ "If-Modified-Since" ] = jQuery.lastModified[ ifModifiedKey ];
677 if ( jQuery.etag[ ifModifiedKey ] ) {
678 requestHeaders[ "If-None-Match" ] = jQuery.etag[ ifModifiedKey ];
682 // Set the Accepts header for the server, depending on the dataType
683 requestHeaders.Accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
684 s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
687 // Check for headers option
688 for ( i in s.headers ) {
689 jqXHR.setRequestHeader( i, s.headers[ i ] );
692 // Allow custom headers/mimetypes and early abort
693 if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
694 // Abort if not done already
700 // Install callbacks on deferreds
701 for ( i in { success: 1, error: 1, complete: 1 } ) {
702 jqXHR[ i ]( s[ i ] );
706 transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
708 // If no transport, we auto-abort
710 done( -1, "No Transport" );
712 jqXHR.readyState = 1;
715 globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
718 if ( s.async && s.timeout > 0 ) {
719 timeoutTimer = setTimeout( function(){
720 jqXHR.abort( "timeout" );
726 transport.send( requestHeaders, done );
728 // Propagate exception as error if not done
731 // Simply rethrow otherwise
741 // Serialize an array of form elements or a set of
742 // key/values into a query string
743 param: function( a, traditional ) {
745 add = function( key, value ) {
746 // If value is a function, invoke it and return its value
747 value = jQuery.isFunction( value ) ? value() : value;
748 s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
751 // Set traditional to true for jQuery <= 1.3.2 behavior.
752 if ( traditional === undefined ) {
753 traditional = jQuery.ajaxSettings.traditional;
756 // If an array was passed in, assume that it is an array of form elements.
757 if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
758 // Serialize the form elements
759 jQuery.each( a, function() {
760 add( this.name, this.value );
764 // If traditional, encode the "old" way (the way 1.3.2 or older
765 // did it), otherwise encode params recursively.
766 for ( var prefix in a ) {
767 buildParams( prefix, a[ prefix ], traditional, add );
771 // Return the resulting serialization
772 return s.join( "&" ).replace( r20, "+" );
776 function buildParams( prefix, obj, traditional, add ) {
777 if ( jQuery.isArray( obj ) && obj.length ) {
778 // Serialize array item.
779 jQuery.each( obj, function( i, v ) {
780 if ( traditional || rbracket.test( prefix ) ) {
781 // Treat each array item as a scalar.
785 // If array item is non-scalar (array or object), encode its
786 // numeric index to resolve deserialization ambiguity issues.
787 // Note that rack (as of 1.0.0) can't currently deserialize
788 // nested arrays properly, and attempting to do so may cause
789 // a server error. Possible fixes are to modify rack's
790 // deserialization algorithm or to provide an option or flag
791 // to force array serialization to be shallow.
792 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
796 } else if ( !traditional && obj != null && typeof obj === "object" ) {
797 // If we see an array here, it is empty and should be treated as an empty
799 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
802 // Serialize object item.
804 for ( var name in obj ) {
805 buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
810 // Serialize scalar item.
815 // This is still on the jQuery object... for now
816 // Want to move this to jQuery.ajax some day
819 // Counter for holding the number of active queries
822 // Last-Modified header cache for next request
828 /* Handles responses to an ajax request:
829 * - sets all responseXXX fields accordingly
830 * - finds the right dataType (mediates between content-type and expected dataType)
831 * - returns the corresponding response
833 function ajaxHandleResponses( s, jqXHR, responses ) {
835 var contents = s.contents,
836 dataTypes = s.dataTypes,
837 responseFields = s.responseFields,
843 // Fill responseXXX fields
844 for( type in responseFields ) {
845 if ( type in responses ) {
846 jqXHR[ responseFields[type] ] = responses[ type ];
850 // Remove auto dataType and get content-type in the process
851 while( dataTypes[ 0 ] === "*" ) {
853 if ( ct === undefined ) {
854 ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
858 // Check if we're dealing with a known content-type
860 for ( type in contents ) {
861 if ( contents[ type ] && contents[ type ].test( ct ) ) {
862 dataTypes.unshift( type );
868 // Check to see if we have a response for the expected dataType
869 if ( dataTypes[ 0 ] in responses ) {
870 finalDataType = dataTypes[ 0 ];
872 // Try convertible dataTypes
873 for ( type in responses ) {
874 if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
875 finalDataType = type;
878 if ( !firstDataType ) {
879 firstDataType = type;
882 // Or just use first one
883 finalDataType = finalDataType || firstDataType;
886 // If we found a dataType
887 // We add the dataType to the list if needed
888 // and return the corresponding response
889 if ( finalDataType ) {
890 if ( finalDataType !== dataTypes[ 0 ] ) {
891 dataTypes.unshift( finalDataType );
893 return responses[ finalDataType ];
897 // Chain conversions given the request and the original response
898 function ajaxConvert( s, response ) {
900 // Apply the dataFilter if provided
901 if ( s.dataFilter ) {
902 response = s.dataFilter( response, s.dataType );
905 var dataTypes = s.dataTypes,
909 length = dataTypes.length,
911 // Current and previous dataTypes
912 current = dataTypes[ 0 ],
914 // Conversion expression
916 // Conversion function
918 // Conversion functions (transitive conversion)
922 // For each dataType in the chain
923 for( i = 1; i < length; i++ ) {
925 // Create converters map
926 // with lowercased keys
928 for( key in s.converters ) {
929 if( typeof key === "string" ) {
930 converters[ key.toLowerCase() ] = s.converters[ key ];
937 current = dataTypes[ i ];
939 // If current is auto dataType, update it to prev
940 if( current === "*" ) {
942 // If no auto and dataTypes are actually different
943 } else if ( prev !== "*" && prev !== current ) {
946 conversion = prev + " " + current;
947 conv = converters[ conversion ] || converters[ "* " + current ];
949 // If there is no direct converter, search transitively
952 for( conv1 in converters ) {
953 tmp = conv1.split( " " );
954 if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
955 conv2 = converters[ tmp[1] + " " + current ];
957 conv1 = converters[ conv1 ];
958 if ( conv1 === true ) {
960 } else if ( conv2 === true ) {
968 // If we found no converter, dispatch an error
969 if ( !( conv || conv2 ) ) {
970 jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
972 // If found converter is not an equivalence
973 if ( conv !== true ) {
974 // Convert with 1 or 2 converters accordingly
975 response = conv ? conv( response ) : conv2( conv1(response) );