10 ], function( jQuery, rnotwhite, nonce, rquery ) {
18 rts = /([?&])_=[^&]*/,
19 rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
20 // #7653, #8125, #8152: local protocol detection
21 rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
22 rnoContent = /^(?:GET|HEAD)$/,
24 rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
27 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
28 * 2) These are called:
29 * - BEFORE asking for a transport
30 * - AFTER param serialization (s.data is a string if s.processData is true)
31 * 3) key is the dataType
32 * 4) the catchall symbol "*" can be used
33 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
37 /* Transports bindings
38 * 1) key is the dataType
39 * 2) the catchall symbol "*" can be used
40 * 3) selection will start with transport dataType and THEN go to "*" if needed
44 // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
45 allTypes = "*/".concat("*");
48 // #8138, IE may throw an exception when accessing
49 // a field from window.location if document.domain has been set
51 ajaxLocation = location.href;
53 // Use the href attribute of an A element
54 // since IE will modify it given document.location
55 ajaxLocation = document.createElement( "a" );
56 ajaxLocation.href = "";
57 ajaxLocation = ajaxLocation.href;
60 // Segment location into parts
61 ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
63 // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
64 function addToPrefiltersOrTransports( structure ) {
66 // dataTypeExpression is optional and defaults to "*"
67 return function( dataTypeExpression, func ) {
69 if ( typeof dataTypeExpression !== "string" ) {
70 func = dataTypeExpression;
71 dataTypeExpression = "*";
76 dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
78 if ( jQuery.isFunction( func ) ) {
79 // For each dataType in the dataTypeExpression
80 while ( (dataType = dataTypes[i++]) ) {
81 // Prepend if requested
82 if ( dataType.charAt( 0 ) === "+" ) {
83 dataType = dataType.slice( 1 ) || "*";
84 (structure[ dataType ] = structure[ dataType ] || []).unshift( func );
88 (structure[ dataType ] = structure[ dataType ] || []).push( func );
95 // Base inspection function for prefilters and transports
96 function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
99 seekingTransport = ( structure === transports );
101 function inspect( dataType ) {
103 inspected[ dataType ] = true;
104 jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
105 var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
106 if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
107 options.dataTypes.unshift( dataTypeOrTransport );
108 inspect( dataTypeOrTransport );
110 } else if ( seekingTransport ) {
111 return !( selected = dataTypeOrTransport );
117 return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
120 // A special extend for ajax options
121 // that takes "flat" options (not to be deep extended)
123 function ajaxExtend( target, src ) {
125 flatOptions = jQuery.ajaxSettings.flatOptions || {};
128 if ( src[ key ] !== undefined ) {
129 ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
133 jQuery.extend( true, target, deep );
139 /* Handles responses to an ajax request:
140 * - finds the right dataType (mediates between content-type and expected dataType)
141 * - returns the corresponding response
143 function ajaxHandleResponses( s, jqXHR, responses ) {
144 var firstDataType, ct, finalDataType, type,
145 contents = s.contents,
146 dataTypes = s.dataTypes;
148 // Remove auto dataType and get content-type in the process
149 while ( dataTypes[ 0 ] === "*" ) {
151 if ( ct === undefined ) {
152 ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
156 // Check if we're dealing with a known content-type
158 for ( type in contents ) {
159 if ( contents[ type ] && contents[ type ].test( ct ) ) {
160 dataTypes.unshift( type );
166 // Check to see if we have a response for the expected dataType
167 if ( dataTypes[ 0 ] in responses ) {
168 finalDataType = dataTypes[ 0 ];
170 // Try convertible dataTypes
171 for ( type in responses ) {
172 if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
173 finalDataType = type;
176 if ( !firstDataType ) {
177 firstDataType = type;
180 // Or just use first one
181 finalDataType = finalDataType || firstDataType;
184 // If we found a dataType
185 // We add the dataType to the list if needed
186 // and return the corresponding response
187 if ( finalDataType ) {
188 if ( finalDataType !== dataTypes[ 0 ] ) {
189 dataTypes.unshift( finalDataType );
191 return responses[ finalDataType ];
195 /* Chain conversions given the request and the original response
196 * Also sets the responseXXX fields on the jqXHR instance
198 function ajaxConvert( s, response, jqXHR, isSuccess ) {
199 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 ] ];
253 // Condense equivalence converters
254 if ( conv === true ) {
255 conv = converters[ conv2 ];
257 // Otherwise, insert the intermediate dataType
258 } else if ( converters[ conv2 ] !== true ) {
260 dataTypes.unshift( tmp[ 1 ] );
268 // Apply converter (if not an equivalence)
269 if ( conv !== true ) {
271 // Unless errors are allowed to bubble, catch and return them
272 if ( conv && s[ "throws" ] ) {
273 response = conv( response );
276 response = conv( response );
278 return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
286 return { state: "success", data: response };
291 // Counter for holding the number of active queries
294 // Last-Modified header cache for next request
301 isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
305 contentType: "application/x-www-form-urlencoded; charset=UTF-8",
322 xml: "application/xml, text/xml",
323 json: "application/json, text/javascript"
334 text: "responseText",
339 // Keys separate source (or catchall "*") and destination types with a single space
342 // Convert anything to text
345 // Text to html (true = no transformation)
348 // Evaluate text as a json expression
349 "text json": jQuery.parseJSON,
352 "text xml": jQuery.parseXML
355 // For options that shouldn't be deep extended:
356 // you can add your own custom options here if
357 // and when you create one that shouldn't be
358 // deep extended (see ajaxExtend)
365 // Creates a full fledged settings object into target
366 // with both ajaxSettings and settings fields.
367 // If target is omitted, writes into ajaxSettings.
368 ajaxSetup: function( target, settings ) {
371 // Building a settings object
372 ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
374 // Extending ajaxSettings
375 ajaxExtend( jQuery.ajaxSettings, target );
378 ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
379 ajaxTransport: addToPrefiltersOrTransports( transports ),
382 ajax: function( url, options ) {
384 // If url is an object, simulate pre-1.5 signature
385 if ( typeof url === "object" ) {
390 // Force options to be an object
391 options = options || {};
393 var // Cross-domain detection vars
397 // URL without anti-cache param
399 // Response headers as string
400 responseHeadersString,
404 // To know if global events are to be dispatched
410 // Create the final options object
411 s = jQuery.ajaxSetup( {}, options ),
413 callbackContext = s.context || s,
414 // Context for global events is callbackContext if it is a DOM node or jQuery collection
415 globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
416 jQuery( callbackContext ) :
419 deferred = jQuery.Deferred(),
420 completeDeferred = jQuery.Callbacks("once memory"),
421 // Status-dependent callbacks
422 statusCode = s.statusCode || {},
423 // Headers (they are sent all at once)
425 requestHeadersNames = {},
428 // Default abort message
429 strAbort = "canceled",
434 // Builds headers hashtable if needed
435 getResponseHeader: function( key ) {
438 if ( !responseHeaders ) {
439 responseHeaders = {};
440 while ( (match = rheaders.exec( responseHeadersString )) ) {
441 responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
444 match = responseHeaders[ key.toLowerCase() ];
446 return match == null ? null : match;
450 getAllResponseHeaders: function() {
451 return state === 2 ? responseHeadersString : null;
455 setRequestHeader: function( name, value ) {
456 var lname = name.toLowerCase();
458 name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
459 requestHeaders[ name ] = value;
464 // Overrides response content-type header
465 overrideMimeType: function( type ) {
472 // Status-dependent callbacks
473 statusCode: function( map ) {
477 for ( code in map ) {
478 // Lazy-add the new callback in a way that preserves old ones
479 statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
482 // Execute the appropriate callbacks
483 jqXHR.always( map[ jqXHR.status ] );
489 // Cancel the request
490 abort: function( statusText ) {
491 var finalText = statusText || strAbort;
493 transport.abort( finalText );
495 done( 0, finalText );
501 deferred.promise( jqXHR ).complete = completeDeferred.add;
502 jqXHR.success = jqXHR.done;
503 jqXHR.error = jqXHR.fail;
505 // Remove hash character (#7531: and string promotion)
506 // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
507 // Handle falsy url in the settings object (#10093: consistency with old signature)
508 // We also use the url parameter if available
509 s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
511 // Alias method option to type as per ticket #12004
512 s.type = options.method || options.type || s.method || s.type;
514 // Extract dataTypes list
515 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
517 // A cross-domain request is in order when we have a protocol:host:port mismatch
518 if ( s.crossDomain == null ) {
519 parts = rurl.exec( s.url.toLowerCase() );
520 s.crossDomain = !!( parts &&
521 ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
522 ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
523 ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
527 // Convert data if not already a string
528 if ( s.data && s.processData && typeof s.data !== "string" ) {
529 s.data = jQuery.param( s.data, s.traditional );
533 inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
535 // If request was aborted inside a prefilter, stop there
540 // We can fire global events as of now if asked to
541 // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
542 fireGlobals = jQuery.event && s.global;
544 // Watch for a new set of requests
545 if ( fireGlobals && jQuery.active++ === 0 ) {
546 jQuery.event.trigger("ajaxStart");
549 // Uppercase the type
550 s.type = s.type.toUpperCase();
552 // Determine if request has content
553 s.hasContent = !rnoContent.test( s.type );
555 // Save the URL in case we're toying with the If-Modified-Since
556 // and/or If-None-Match header later on
559 // More options handling for requests with no content
560 if ( !s.hasContent ) {
562 // If data is available, append data to url
564 cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
565 // #9682: remove data so that it's not used in an eventual retry
569 // Add anti-cache in url if needed
570 if ( s.cache === false ) {
571 s.url = rts.test( cacheURL ) ?
573 // If there is already a '_' parameter, set its value
574 cacheURL.replace( rts, "$1_=" + nonce++ ) :
576 // Otherwise add one to the end
577 cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
581 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
582 if ( s.ifModified ) {
583 if ( jQuery.lastModified[ cacheURL ] ) {
584 jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
586 if ( jQuery.etag[ cacheURL ] ) {
587 jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
591 // Set the correct header, if data is being sent
592 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
593 jqXHR.setRequestHeader( "Content-Type", s.contentType );
596 // Set the Accepts header for the server, depending on the dataType
597 jqXHR.setRequestHeader(
599 s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
600 s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
604 // Check for headers option
605 for ( i in s.headers ) {
606 jqXHR.setRequestHeader( i, s.headers[ i ] );
609 // Allow custom headers/mimetypes and early abort
610 if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
611 // Abort if not done already and return
612 return jqXHR.abort();
615 // aborting is no longer a cancellation
618 // Install callbacks on deferreds
619 for ( i in { success: 1, error: 1, complete: 1 } ) {
620 jqXHR[ i ]( s[ i ] );
624 transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
626 // If no transport, we auto-abort
628 done( -1, "No Transport" );
630 jqXHR.readyState = 1;
634 globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
637 if ( s.async && s.timeout > 0 ) {
638 timeoutTimer = setTimeout(function() {
639 jqXHR.abort("timeout");
645 transport.send( requestHeaders, done );
647 // Propagate exception as error if not done
650 // Simply rethrow otherwise
657 // Callback for when everything is done
658 function done( status, nativeStatusText, responses, headers ) {
659 var isSuccess, success, error, response, modified,
660 statusText = nativeStatusText;
667 // State is "done" now
670 // Clear timeout if it exists
671 if ( timeoutTimer ) {
672 clearTimeout( timeoutTimer );
675 // Dereference transport for early garbage collection
676 // (no matter how long the jqXHR object will be used)
677 transport = undefined;
679 // Cache response headers
680 responseHeadersString = headers || "";
683 jqXHR.readyState = status > 0 ? 4 : 0;
685 // Determine if successful
686 isSuccess = status >= 200 && status < 300 || status === 304;
690 response = ajaxHandleResponses( s, jqXHR, responses );
693 // Convert no matter what (that way responseXXX fields are always set)
694 response = ajaxConvert( s, response, jqXHR, isSuccess );
696 // If successful, handle type chaining
699 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
700 if ( s.ifModified ) {
701 modified = jqXHR.getResponseHeader("Last-Modified");
703 jQuery.lastModified[ cacheURL ] = modified;
705 modified = jqXHR.getResponseHeader("etag");
707 jQuery.etag[ cacheURL ] = modified;
712 if ( status === 204 || s.type === "HEAD" ) {
713 statusText = "nocontent";
716 } else if ( status === 304 ) {
717 statusText = "notmodified";
719 // If we have data, let's convert it
721 statusText = response.state;
722 success = response.data;
723 error = response.error;
727 // We extract error from statusText
728 // then normalize statusText and status for non-aborts
730 if ( status || !statusText ) {
731 statusText = "error";
738 // Set data for the fake xhr object
739 jqXHR.status = status;
740 jqXHR.statusText = ( nativeStatusText || statusText ) + "";
744 deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
746 deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
749 // Status-dependent callbacks
750 jqXHR.statusCode( statusCode );
751 statusCode = undefined;
754 globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
755 [ jqXHR, s, isSuccess ? success : error ] );
759 completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
762 globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
763 // Handle the global AJAX counter
764 if ( !( --jQuery.active ) ) {
765 jQuery.event.trigger("ajaxStop");
773 getJSON: function( url, data, callback ) {
774 return jQuery.get( url, data, callback, "json" );
777 getScript: function( url, callback ) {
778 return jQuery.get( url, undefined, callback, "script" );
782 jQuery.each( [ "get", "post" ], function( i, method ) {
783 jQuery[ method ] = function( url, data, callback, type ) {
784 // shift arguments if data argument was omitted
785 if ( jQuery.isFunction( data ) ) {
786 type = type || callback;