14 "./serialize" // jQuery.param
15 ], function( jQuery, document, isFunction, rnothtmlwhite, location, nonce, rquery ) {
22 rantiCache = /([?&])_=[^&]*/,
23 rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
25 // #7653, #8125, #8152: local protocol detection
26 rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
27 rnoContent = /^(?:GET|HEAD)$/,
31 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
32 * 2) These are called:
33 * - BEFORE asking for a transport
34 * - AFTER param serialization (s.data is a string if s.processData is true)
35 * 3) key is the dataType
36 * 4) the catchall symbol "*" can be used
37 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
41 /* Transports bindings
42 * 1) key is the dataType
43 * 2) the catchall symbol "*" can be used
44 * 3) selection will start with transport dataType and THEN go to "*" if needed
48 // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
49 allTypes = "*/".concat( "*" ),
51 // Anchor tag for parsing the document origin
52 originAnchor = document.createElement( "a" );
53 originAnchor.href = location.href;
55 // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
56 function addToPrefiltersOrTransports( structure ) {
58 // dataTypeExpression is optional and defaults to "*"
59 return function( dataTypeExpression, func ) {
61 if ( typeof dataTypeExpression !== "string" ) {
62 func = dataTypeExpression;
63 dataTypeExpression = "*";
68 dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || [];
70 if ( isFunction( func ) ) {
72 // For each dataType in the dataTypeExpression
73 while ( ( dataType = dataTypes[ i++ ] ) ) {
75 // Prepend if requested
76 if ( dataType[ 0 ] === "+" ) {
77 dataType = dataType.slice( 1 ) || "*";
78 ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );
82 ( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
89 // Base inspection function for prefilters and transports
90 function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
93 seekingTransport = ( structure === transports );
95 function inspect( dataType ) {
97 inspected[ dataType ] = true;
98 jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
99 var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
100 if ( typeof dataTypeOrTransport === "string" &&
101 !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
103 options.dataTypes.unshift( dataTypeOrTransport );
104 inspect( dataTypeOrTransport );
106 } else if ( seekingTransport ) {
107 return !( selected = dataTypeOrTransport );
113 return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
116 // A special extend for ajax options
117 // that takes "flat" options (not to be deep extended)
119 function ajaxExtend( target, src ) {
121 flatOptions = jQuery.ajaxSettings.flatOptions || {};
124 if ( src[ key ] !== undefined ) {
125 ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
129 jQuery.extend( true, target, deep );
135 /* Handles responses to an ajax request:
136 * - finds the right dataType (mediates between content-type and expected dataType)
137 * - returns the corresponding response
139 function ajaxHandleResponses( s, jqXHR, responses ) {
141 var ct, type, finalDataType, firstDataType,
142 contents = s.contents,
143 dataTypes = s.dataTypes;
145 // Remove auto dataType and get content-type in the process
146 while ( dataTypes[ 0 ] === "*" ) {
148 if ( ct === undefined ) {
149 ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
153 // Check if we're dealing with a known content-type
155 for ( type in contents ) {
156 if ( contents[ type ] && contents[ type ].test( ct ) ) {
157 dataTypes.unshift( type );
163 // Check to see if we have a response for the expected dataType
164 if ( dataTypes[ 0 ] in responses ) {
165 finalDataType = dataTypes[ 0 ];
168 // Try convertible dataTypes
169 for ( type in responses ) {
170 if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
171 finalDataType = type;
174 if ( !firstDataType ) {
175 firstDataType = type;
179 // Or just use first one
180 finalDataType = finalDataType || firstDataType;
183 // If we found a dataType
184 // We add the dataType to the list if needed
185 // and return the corresponding response
186 if ( finalDataType ) {
187 if ( finalDataType !== dataTypes[ 0 ] ) {
188 dataTypes.unshift( finalDataType );
190 return responses[ finalDataType ];
194 /* Chain conversions given the request and the original response
195 * Also sets the responseXXX fields on the jqXHR instance
197 function ajaxConvert( s, response, jqXHR, isSuccess ) {
198 var conv2, current, conv, tmp, prev,
201 // Work with a copy of dataTypes in case we need to modify it for conversion
202 dataTypes = s.dataTypes.slice();
204 // Create converters map with lowercased keys
205 if ( dataTypes[ 1 ] ) {
206 for ( conv in s.converters ) {
207 converters[ conv.toLowerCase() ] = s.converters[ conv ];
211 current = dataTypes.shift();
213 // Convert to each sequential dataType
216 if ( s.responseFields[ current ] ) {
217 jqXHR[ s.responseFields[ current ] ] = response;
220 // Apply the dataFilter if provided
221 if ( !prev && isSuccess && s.dataFilter ) {
222 response = s.dataFilter( response, s.dataType );
226 current = dataTypes.shift();
230 // There's only work to do if current dataType is non-auto
231 if ( current === "*" ) {
235 // Convert response if prev dataType is non-auto and differs from current
236 } else if ( prev !== "*" && prev !== current ) {
238 // Seek a direct converter
239 conv = converters[ prev + " " + current ] || converters[ "* " + current ];
241 // If none found, seek a pair
243 for ( conv2 in converters ) {
245 // If conv2 outputs current
246 tmp = conv2.split( " " );
247 if ( tmp[ 1 ] === current ) {
249 // If prev can be converted to accepted input
250 conv = converters[ prev + " " + tmp[ 0 ] ] ||
251 converters[ "* " + tmp[ 0 ] ];
254 // Condense equivalence converters
255 if ( conv === true ) {
256 conv = converters[ conv2 ];
258 // Otherwise, insert the intermediate dataType
259 } else if ( converters[ conv2 ] !== true ) {
261 dataTypes.unshift( tmp[ 1 ] );
269 // Apply converter (if not an equivalence)
270 if ( conv !== true ) {
272 // Unless errors are allowed to bubble, catch and return them
273 if ( conv && s.throws ) {
274 response = conv( response );
277 response = conv( response );
280 state: "parsererror",
281 error: conv ? e : "No conversion from " + prev + " to " + current
290 return { state: "success", data: response };
295 // Counter for holding the number of active queries
298 // Last-Modified header cache for next request
305 isLocal: rlocalProtocol.test( location.protocol ),
309 contentType: "application/x-www-form-urlencoded; charset=UTF-8",
327 xml: "application/xml, text/xml",
328 json: "application/json, text/javascript"
339 text: "responseText",
344 // Keys separate source (or catchall "*") and destination types with a single space
347 // Convert anything to text
350 // Text to html (true = no transformation)
353 // Evaluate text as a json expression
354 "text json": JSON.parse,
357 "text xml": jQuery.parseXML
360 // For options that shouldn't be deep extended:
361 // you can add your own custom options here if
362 // and when you create one that shouldn't be
363 // deep extended (see ajaxExtend)
370 // Creates a full fledged settings object into target
371 // with both ajaxSettings and settings fields.
372 // If target is omitted, writes into ajaxSettings.
373 ajaxSetup: function( target, settings ) {
376 // Building a settings object
377 ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
379 // Extending ajaxSettings
380 ajaxExtend( jQuery.ajaxSettings, target );
383 ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
384 ajaxTransport: addToPrefiltersOrTransports( transports ),
387 ajax: function( url, options ) {
389 // If url is an object, simulate pre-1.5 signature
390 if ( typeof url === "object" ) {
395 // Force options to be an object
396 options = options || {};
400 // URL without anti-cache param
404 responseHeadersString,
413 // Request state (becomes false upon send and true upon completion)
416 // To know if global events are to be dispatched
422 // uncached part of the url
425 // Create the final options object
426 s = jQuery.ajaxSetup( {}, options ),
429 callbackContext = s.context || s,
431 // Context for global events is callbackContext if it is a DOM node or jQuery collection
432 globalEventContext = s.context &&
433 ( callbackContext.nodeType || callbackContext.jquery ) ?
434 jQuery( callbackContext ) :
438 deferred = jQuery.Deferred(),
439 completeDeferred = jQuery.Callbacks( "once memory" ),
441 // Status-dependent callbacks
442 statusCode = s.statusCode || {},
444 // Headers (they are sent all at once)
446 requestHeadersNames = {},
448 // Default abort message
449 strAbort = "canceled",
455 // Builds headers hashtable if needed
456 getResponseHeader: function( key ) {
459 if ( !responseHeaders ) {
460 responseHeaders = {};
461 while ( ( match = rheaders.exec( responseHeadersString ) ) ) {
462 responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
465 match = responseHeaders[ key.toLowerCase() ];
467 return match == null ? null : match;
471 getAllResponseHeaders: function() {
472 return completed ? responseHeadersString : null;
476 setRequestHeader: function( name, value ) {
477 if ( completed == null ) {
478 name = requestHeadersNames[ name.toLowerCase() ] =
479 requestHeadersNames[ name.toLowerCase() ] || name;
480 requestHeaders[ name ] = value;
485 // Overrides response content-type header
486 overrideMimeType: function( type ) {
487 if ( completed == null ) {
493 // Status-dependent callbacks
494 statusCode: function( map ) {
499 // Execute the appropriate callbacks
500 jqXHR.always( map[ jqXHR.status ] );
503 // Lazy-add the new callbacks in a way that preserves old ones
504 for ( code in map ) {
505 statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
512 // Cancel the request
513 abort: function( statusText ) {
514 var finalText = statusText || strAbort;
516 transport.abort( finalText );
518 done( 0, finalText );
524 deferred.promise( jqXHR );
526 // Add protocol if not provided (prefilters might expect it)
527 // Handle falsy url in the settings object (#10093: consistency with old signature)
528 // We also use the url parameter if available
529 s.url = ( ( url || s.url || location.href ) + "" )
530 .replace( rprotocol, location.protocol + "//" );
532 // Alias method option to type as per ticket #12004
533 s.type = options.method || options.type || s.method || s.type;
535 // Extract dataTypes list
536 s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ];
538 // A cross-domain request is in order when the origin doesn't match the current origin.
539 if ( s.crossDomain == null ) {
540 urlAnchor = document.createElement( "a" );
542 // Support: IE <=8 - 11, Edge 12 - 15
543 // IE throws exception on accessing the href property if url is malformed,
544 // e.g. http://example.com:80x/
546 urlAnchor.href = s.url;
548 // Support: IE <=8 - 11 only
549 // Anchor's host property isn't correctly set when s.url is relative
550 urlAnchor.href = urlAnchor.href;
551 s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !==
552 urlAnchor.protocol + "//" + urlAnchor.host;
555 // If there is an error parsing the URL, assume it is crossDomain,
556 // it can be rejected by the transport if it is invalid
557 s.crossDomain = true;
561 // Convert data if not already a string
562 if ( s.data && s.processData && typeof s.data !== "string" ) {
563 s.data = jQuery.param( s.data, s.traditional );
567 inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
569 // If request was aborted inside a prefilter, stop there
574 // We can fire global events as of now if asked to
575 // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
576 fireGlobals = jQuery.event && s.global;
578 // Watch for a new set of requests
579 if ( fireGlobals && jQuery.active++ === 0 ) {
580 jQuery.event.trigger( "ajaxStart" );
583 // Uppercase the type
584 s.type = s.type.toUpperCase();
586 // Determine if request has content
587 s.hasContent = !rnoContent.test( s.type );
589 // Save the URL in case we're toying with the If-Modified-Since
590 // and/or If-None-Match header later on
591 // Remove hash to simplify url manipulation
592 cacheURL = s.url.replace( rhash, "" );
594 // More options handling for requests with no content
595 if ( !s.hasContent ) {
597 // Remember the hash so we can put it back
598 uncached = s.url.slice( cacheURL.length );
600 // If data is available and should be processed, append data to url
601 if ( s.data && ( s.processData || typeof s.data === "string" ) ) {
602 cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data;
604 // #9682: remove data so that it's not used in an eventual retry
608 // Add or update anti-cache param if needed
609 if ( s.cache === false ) {
610 cacheURL = cacheURL.replace( rantiCache, "$1" );
611 uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached;
614 // Put hash and anti-cache on the URL that will be requested (gh-1732)
615 s.url = cacheURL + uncached;
617 // Change '%20' to '+' if this is encoded form body content (gh-2658)
618 } else if ( s.data && s.processData &&
619 ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) {
620 s.data = s.data.replace( r20, "+" );
623 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
624 if ( s.ifModified ) {
625 if ( jQuery.lastModified[ cacheURL ] ) {
626 jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
628 if ( jQuery.etag[ cacheURL ] ) {
629 jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
633 // Set the correct header, if data is being sent
634 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
635 jqXHR.setRequestHeader( "Content-Type", s.contentType );
638 // Set the Accepts header for the server, depending on the dataType
639 jqXHR.setRequestHeader(
641 s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
642 s.accepts[ s.dataTypes[ 0 ] ] +
643 ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
647 // Check for headers option
648 for ( i in s.headers ) {
649 jqXHR.setRequestHeader( i, s.headers[ i ] );
652 // Allow custom headers/mimetypes and early abort
654 ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) {
656 // Abort if not done already and return
657 return jqXHR.abort();
660 // Aborting is no longer a cancellation
663 // Install callbacks on deferreds
664 completeDeferred.add( s.complete );
665 jqXHR.done( s.success );
666 jqXHR.fail( s.error );
669 transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
671 // If no transport, we auto-abort
673 done( -1, "No Transport" );
675 jqXHR.readyState = 1;
679 globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
682 // If request was aborted inside ajaxSend, stop there
688 if ( s.async && s.timeout > 0 ) {
689 timeoutTimer = window.setTimeout( function() {
690 jqXHR.abort( "timeout" );
696 transport.send( requestHeaders, done );
699 // Rethrow post-completion exceptions
704 // Propagate others as results
709 // Callback for when everything is done
710 function done( status, nativeStatusText, responses, headers ) {
711 var isSuccess, success, error, response, modified,
712 statusText = nativeStatusText;
714 // Ignore repeat invocations
721 // Clear timeout if it exists
722 if ( timeoutTimer ) {
723 window.clearTimeout( timeoutTimer );
726 // Dereference transport for early garbage collection
727 // (no matter how long the jqXHR object will be used)
728 transport = undefined;
730 // Cache response headers
731 responseHeadersString = headers || "";
734 jqXHR.readyState = status > 0 ? 4 : 0;
736 // Determine if successful
737 isSuccess = status >= 200 && status < 300 || status === 304;
741 response = ajaxHandleResponses( s, jqXHR, responses );
744 // Convert no matter what (that way responseXXX fields are always set)
745 response = ajaxConvert( s, response, jqXHR, isSuccess );
747 // If successful, handle type chaining
750 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
751 if ( s.ifModified ) {
752 modified = jqXHR.getResponseHeader( "Last-Modified" );
754 jQuery.lastModified[ cacheURL ] = modified;
756 modified = jqXHR.getResponseHeader( "etag" );
758 jQuery.etag[ cacheURL ] = modified;
763 if ( status === 204 || s.type === "HEAD" ) {
764 statusText = "nocontent";
767 } else if ( status === 304 ) {
768 statusText = "notmodified";
770 // If we have data, let's convert it
772 statusText = response.state;
773 success = response.data;
774 error = response.error;
779 // Extract error from statusText and normalize for non-aborts
781 if ( status || !statusText ) {
782 statusText = "error";
789 // Set data for the fake xhr object
790 jqXHR.status = status;
791 jqXHR.statusText = ( nativeStatusText || statusText ) + "";
795 deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
797 deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
800 // Status-dependent callbacks
801 jqXHR.statusCode( statusCode );
802 statusCode = undefined;
805 globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
806 [ jqXHR, s, isSuccess ? success : error ] );
810 completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
813 globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
815 // Handle the global AJAX counter
816 if ( !( --jQuery.active ) ) {
817 jQuery.event.trigger( "ajaxStop" );
825 getJSON: function( url, data, callback ) {
826 return jQuery.get( url, data, callback, "json" );
829 getScript: function( url, callback ) {
830 return jQuery.get( url, undefined, callback, "script" );
834 jQuery.each( [ "get", "post" ], function( i, method ) {
835 jQuery[ method ] = function( url, data, callback, type ) {
837 // Shift arguments if data argument was omitted
838 if ( isFunction( data ) ) {
839 type = type || callback;
844 // The url can be an options object (which then must have .url)
845 return jQuery.ajax( jQuery.extend( {
851 }, jQuery.isPlainObject( url ) && url ) );