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 rucWord = /(^|\-)([a-z])/g,
19 rurl = /^([\w\+\.\-]+:)\/\/([^\/?#:]*)(?::(\d+))?/,
21 // Keep a copy of the old load method
22 _load = jQuery.fn.load,
25 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
26 * 2) These are called:
27 * - BEFORE asking for a transport
28 * - AFTER param serialization (s.data is a string if s.processData is true)
29 * 3) key is the dataType
30 * 4) the catchall symbol "*" can be used
31 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
35 /* Transports bindings
36 * 1) key is the dataType
37 * 2) the catchall symbol "*" can be used
38 * 3) selection will start with transport dataType and THEN go to "*" if needed
45 // Document location segments
48 // #8138, IE may throw an exception when accessing
49 // a field from document.location if document.domain has been set
51 ajaxLocation = document.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 = "*";
74 if ( jQuery.isFunction( func ) ) {
75 var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
77 length = dataTypes.length,
82 // For each dataType in the dataTypeExpression
83 for(; i < length; i++ ) {
84 dataType = dataTypes[ i ];
85 // We control if we're asked to add before
86 // any existing element
87 placeBefore = /^\+/.test( dataType );
89 dataType = dataType.substr( 1 ) || "*";
91 list = structure[ dataType ] = structure[ dataType ] || [];
92 // then we add to the structure accordingly
93 list[ placeBefore ? "unshift" : "push" ]( func );
99 //Base inspection function for prefilters and transports
100 function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
101 dataType /* internal */, inspected /* internal */ ) {
103 dataType = dataType || options.dataTypes[ 0 ];
104 inspected = inspected || {};
106 inspected[ dataType ] = true;
108 var list = structure[ dataType ],
110 length = list ? list.length : 0,
111 executeOnly = ( structure === prefilters ),
114 for(; i < length && ( executeOnly || !selection ); i++ ) {
115 selection = list[ i ]( options, originalOptions, jqXHR );
116 // If we got redirected to another dataType
117 // we try there if executing only and not done already
118 if ( typeof selection === "string" ) {
119 if ( !executeOnly || inspected[ selection ] ) {
120 selection = undefined;
122 options.dataTypes.unshift( selection );
123 selection = inspectPrefiltersOrTransports(
124 structure, options, originalOptions, jqXHR, selection, inspected );
128 // If we're only executing or nothing was selected
129 // we try the catchall dataType if not done already
130 if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
131 selection = inspectPrefiltersOrTransports(
132 structure, options, originalOptions, jqXHR, "*", inspected );
134 // unnecessary when only executing (prefilters)
135 // but it'll be ignored by the caller in that case
140 load: function( url, params, callback ) {
141 if ( typeof url !== "string" && _load ) {
142 return _load.apply( this, arguments );
144 // Don't do a request if no elements are being requested
145 } else if ( !this.length ) {
149 var off = url.indexOf( " " );
151 var selector = url.slice( off, url.length );
152 url = url.slice( 0, off );
155 // Default to a GET request
158 // If the second parameter was provided
160 // If it's a function
161 if ( jQuery.isFunction( params ) ) {
162 // We assume that it's the callback
166 // Otherwise, build a param string
167 } else if ( typeof params === "object" ) {
168 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
175 // Request the remote document
181 // Complete callback (responseText is used internally)
182 complete: function( jqXHR, status, responseText ) {
183 // Store the response as specified by the jqXHR object
184 responseText = jqXHR.responseText;
185 // If successful, inject the HTML into all the matched elements
186 if ( jqXHR.isResolved() ) {
187 // #4825: Get the actual response in case
188 // a dataFilter is present in ajaxSettings
189 jqXHR.done(function( r ) {
192 // See if a selector was specified
193 self.html( selector ?
194 // Create a dummy div to hold the results
196 // inject the contents of the document in, removing the scripts
197 // to avoid any 'Permission Denied' errors in IE
198 .append(responseText.replace(rscript, ""))
200 // Locate the specified elements
203 // If not, just inject the full result
208 self.each( callback, [ responseText, status, jqXHR ] );
216 serialize: function() {
217 return jQuery.param( this.serializeArray() );
220 serializeArray: function() {
221 return this.map(function(){
222 return this.elements ? jQuery.makeArray( this.elements ) : this;
225 return this.name && !this.disabled &&
226 ( this.checked || rselectTextarea.test( this.nodeName ) ||
227 rinput.test( this.type ) );
229 .map(function( i, elem ){
230 var val = jQuery( this ).val();
234 jQuery.isArray( val ) ?
235 jQuery.map( val, function( val, i ){
236 return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
238 { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
243 // Attach a bunch of functions for handling common AJAX events
244 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
245 jQuery.fn[ o ] = function( f ){
246 return this.bind( o, f );
250 jQuery.each( [ "get", "post" ], function( i, method ) {
251 jQuery[ method ] = function( url, data, callback, type ) {
252 // shift arguments if data argument was omitted
253 if ( jQuery.isFunction( data ) ) {
254 type = type || callback;
271 getScript: function( url, callback ) {
272 return jQuery.get( url, null, callback, "script" );
275 getJSON: function( url, data, callback ) {
276 return jQuery.get( url, data, callback, "json" );
279 ajaxSetup: function( settings ) {
280 jQuery.extend( true, jQuery.ajaxSettings, settings );
281 if ( settings.context ) {
282 jQuery.ajaxSettings.context = settings.context;
288 isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
291 contentType: "application/x-www-form-urlencoded",
307 xml: "application/xml, text/xml",
310 json: "application/json, text/javascript",
325 // List of data converters
326 // 1) key format is "source_type destination_type" (a single space in-between)
327 // 2) the catchall symbol "*" can be used for source_type
330 // Convert anything to text
331 "* text": window.String,
333 // Text to html (true = no transformation)
336 // Evaluate text as a json expression
337 "text json": jQuery.parseJSON,
340 "text xml": jQuery.parseXML
344 ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
345 ajaxTransport: addToPrefiltersOrTransports( transports ),
348 ajax: function( url, options ) {
350 // If url is an object, simulate pre-1.5 signature
351 if ( typeof url === "object" ) {
356 // Force options to be an object
357 options = options || {};
359 var // Create the final options object
360 s = jQuery.extend( true, {}, jQuery.ajaxSettings, options ),
362 // We force the original context if it exists
363 // or take it from jQuery.ajaxSettings otherwise
364 // (plain objects used as context get extended)
366 ( s.context = ( "context" in options ? options : jQuery.ajaxSettings ).context ) || s,
367 // Context for global events
368 // It's the callbackContext if one was provided in the options
369 // and if it's a DOM node or a jQuery collection
370 globalEventContext = callbackContext !== s &&
371 ( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
372 jQuery( callbackContext ) : jQuery.event,
374 deferred = jQuery.Deferred(),
375 completeDeferred = jQuery._Deferred(),
376 // Status-dependent callbacks
377 statusCode = s.statusCode || {},
380 // Headers (they are sent all at once)
383 responseHeadersString,
389 // Cross-domain detection vars
393 // To know if global events are to be dispatched
403 setRequestHeader: function( name, value ) {
405 requestHeaders[ name.toLowerCase().replace( rucWord, function( _, $1, $2 ) {
406 return $1 + $2.toUpperCase();
413 getAllResponseHeaders: function() {
414 return state === 2 ? responseHeadersString : null;
417 // Builds headers hashtable if needed
418 getResponseHeader: function( key ) {
421 if ( !responseHeaders ) {
422 responseHeaders = {};
423 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
424 responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
427 match = responseHeaders[ key.toLowerCase() ];
429 return match || null;
432 // Overrides response content-type header
433 overrideMimeType: function( type ) {
440 // Cancel the request
441 abort: function( statusText ) {
442 statusText = statusText || "abort";
444 transport.abort( statusText );
446 done( 0, statusText );
451 // Callback for when everything is done
452 // It is defined here because jslint complains if it is declared
453 // at the end of the function (which would be more logical and readable)
454 function done( status, statusText, responses, headers ) {
461 // State is "done" now
464 // Clear timeout if it exists
465 if ( timeoutTimer ) {
466 clearTimeout( timeoutTimer );
469 // Dereference transport for early garbage collection
470 // (no matter how long the jqXHR object will be used)
471 transport = undefined;
473 // Cache response headers
474 responseHeadersString = headers || "";
477 jqXHR.readyState = status ? 4 : 0;
482 response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
486 // If successful, handle type chaining
487 if ( status >= 200 && status < 300 || status === 304 ) {
489 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
490 if ( s.ifModified ) {
492 if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
493 jQuery.lastModified[ ifModifiedKey ] = lastModified;
495 if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
496 jQuery.etag[ ifModifiedKey ] = etag;
501 if ( status === 304 ) {
503 statusText = "notmodified";
510 success = ajaxConvert( s, response );
511 statusText = "success";
514 // We have a parsererror
515 statusText = "parsererror";
520 // We extract error from statusText
521 // then normalize statusText and status for non-aborts
523 if( !statusText || status ) {
524 statusText = "error";
531 // Set data for the fake xhr object
532 jqXHR.status = status;
533 jqXHR.statusText = statusText;
537 deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
539 deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
542 // Status-dependent callbacks
543 jqXHR.statusCode( statusCode );
544 statusCode = undefined;
547 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
548 [ jqXHR, s, isSuccess ? success : error ] );
552 completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );
555 globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] );
556 // Handle the global AJAX counter
557 if ( !( --jQuery.active ) ) {
558 jQuery.event.trigger( "ajaxStop" );
564 deferred.promise( jqXHR );
565 jqXHR.success = jqXHR.done;
566 jqXHR.error = jqXHR.fail;
567 jqXHR.complete = completeDeferred.done;
569 // Status-dependent callbacks
570 jqXHR.statusCode = function( map ) {
575 statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
578 tmp = map[ jqXHR.status ];
579 jqXHR.then( tmp, tmp );
585 // Remove hash character (#7531: and string promotion)
586 // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
587 // We also use the url parameter if available
588 s.url = ( "" + ( url || s.url ) ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
590 // Extract dataTypes list
591 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
593 // Determine if a cross-domain request is in order
594 if ( !s.crossDomain ) {
595 parts = rurl.exec( s.url.toLowerCase() );
596 s.crossDomain = !!( parts &&
597 ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
598 ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
599 ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
603 // Convert data if not already a string
604 if ( s.data && s.processData && typeof s.data !== "string" ) {
605 s.data = jQuery.param( s.data, s.traditional );
609 inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
611 // If request was aborted inside a prefiler, stop there
616 // We can fire global events as of now if asked to
617 fireGlobals = s.global;
619 // Uppercase the type
620 s.type = s.type.toUpperCase();
622 // Determine if request has content
623 s.hasContent = !rnoContent.test( s.type );
625 // Watch for a new set of requests
626 if ( fireGlobals && jQuery.active++ === 0 ) {
627 jQuery.event.trigger( "ajaxStart" );
630 // More options handling for requests with no content
631 if ( !s.hasContent ) {
633 // If data is available, append data to url
635 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
638 // Get ifModifiedKey before adding the anti-cache parameter
639 ifModifiedKey = s.url;
641 // Add anti-cache in url if needed
642 if ( s.cache === false ) {
644 var ts = jQuery.now(),
645 // try replacing _= if it is there
646 ret = s.url.replace( rts, "$1_=" + ts );
648 // if nothing was replaced, add timestamp to the end
649 s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
653 // Set the correct header, if data is being sent
654 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
655 requestHeaders[ "Content-Type" ] = s.contentType;
658 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
659 if ( s.ifModified ) {
660 ifModifiedKey = ifModifiedKey || s.url;
661 if ( jQuery.lastModified[ ifModifiedKey ] ) {
662 requestHeaders[ "If-Modified-Since" ] = jQuery.lastModified[ ifModifiedKey ];
664 if ( jQuery.etag[ ifModifiedKey ] ) {
665 requestHeaders[ "If-None-Match" ] = jQuery.etag[ ifModifiedKey ];
669 // Set the Accepts header for the server, depending on the dataType
670 requestHeaders.Accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
671 s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
674 // Check for headers option
675 for ( i in s.headers ) {
676 jqXHR.setRequestHeader( i, s.headers[ i ] );
679 // Allow custom headers/mimetypes and early abort
680 if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
681 // Abort if not done already
687 // Install callbacks on deferreds
688 for ( i in { success: 1, error: 1, complete: 1 } ) {
689 jqXHR[ i ]( s[ i ] );
693 transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
695 // If no transport, we auto-abort
697 done( -1, "No Transport" );
699 jqXHR.readyState = 1;
702 globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
705 if ( s.async && s.timeout > 0 ) {
706 timeoutTimer = setTimeout( function(){
707 jqXHR.abort( "timeout" );
713 transport.send( requestHeaders, done );
715 // Propagate exception as error if not done
718 // Simply rethrow otherwise
728 // Serialize an array of form elements or a set of
729 // key/values into a query string
730 param: function( a, traditional ) {
732 add = function( key, value ) {
733 // If value is a function, invoke it and return its value
734 value = jQuery.isFunction( value ) ? value() : value;
735 s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
738 // Set traditional to true for jQuery <= 1.3.2 behavior.
739 if ( traditional === undefined ) {
740 traditional = jQuery.ajaxSettings.traditional;
743 // If an array was passed in, assume that it is an array of form elements.
744 if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
745 // Serialize the form elements
746 jQuery.each( a, function() {
747 add( this.name, this.value );
751 // If traditional, encode the "old" way (the way 1.3.2 or older
752 // did it), otherwise encode params recursively.
753 for ( var prefix in a ) {
754 buildParams( prefix, a[ prefix ], traditional, add );
758 // Return the resulting serialization
759 return s.join( "&" ).replace( r20, "+" );
763 function buildParams( prefix, obj, traditional, add ) {
764 if ( jQuery.isArray( obj ) && obj.length ) {
765 // Serialize array item.
766 jQuery.each( obj, function( i, v ) {
767 if ( traditional || rbracket.test( prefix ) ) {
768 // Treat each array item as a scalar.
772 // If array item is non-scalar (array or object), encode its
773 // numeric index to resolve deserialization ambiguity issues.
774 // Note that rack (as of 1.0.0) can't currently deserialize
775 // nested arrays properly, and attempting to do so may cause
776 // a server error. Possible fixes are to modify rack's
777 // deserialization algorithm or to provide an option or flag
778 // to force array serialization to be shallow.
779 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
783 } else if ( !traditional && obj != null && typeof obj === "object" ) {
784 // If we see an array here, it is empty and should be treated as an empty
786 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
789 // Serialize object item.
791 for ( var name in obj ) {
792 buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
797 // Serialize scalar item.
802 // This is still on the jQuery object... for now
803 // Want to move this to jQuery.ajax some day
806 // Counter for holding the number of active queries
809 // Last-Modified header cache for next request
815 /* Handles responses to an ajax request:
816 * - sets all responseXXX fields accordingly
817 * - finds the right dataType (mediates between content-type and expected dataType)
818 * - returns the corresponding response
820 function ajaxHandleResponses( s, jqXHR, responses ) {
822 var contents = s.contents,
823 dataTypes = s.dataTypes,
824 responseFields = s.responseFields,
830 // Fill responseXXX fields
831 for( type in responseFields ) {
832 if ( type in responses ) {
833 jqXHR[ responseFields[type] ] = responses[ type ];
837 // Remove auto dataType and get content-type in the process
838 while( dataTypes[ 0 ] === "*" ) {
840 if ( ct === undefined ) {
841 ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
845 // Check if we're dealing with a known content-type
847 for ( type in contents ) {
848 if ( contents[ type ] && contents[ type ].test( ct ) ) {
849 dataTypes.unshift( type );
855 // Check to see if we have a response for the expected dataType
856 if ( dataTypes[ 0 ] in responses ) {
857 finalDataType = dataTypes[ 0 ];
859 // Try convertible dataTypes
860 for ( type in responses ) {
861 if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
862 finalDataType = type;
865 if ( !firstDataType ) {
866 firstDataType = type;
869 // Or just use first one
870 finalDataType = finalDataType || firstDataType;
873 // If we found a dataType
874 // We add the dataType to the list if needed
875 // and return the corresponding response
876 if ( finalDataType ) {
877 if ( finalDataType !== dataTypes[ 0 ] ) {
878 dataTypes.unshift( finalDataType );
880 return responses[ finalDataType ];
884 // Chain conversions given the request and the original response
885 function ajaxConvert( s, response ) {
887 // Apply the dataFilter if provided
888 if ( s.dataFilter ) {
889 response = s.dataFilter( response, s.dataType );
892 var dataTypes = s.dataTypes,
896 length = dataTypes.length,
898 // Current and previous dataTypes
899 current = dataTypes[ 0 ],
901 // Conversion expression
903 // Conversion function
905 // Conversion functions (transitive conversion)
909 // For each dataType in the chain
910 for( i = 1; i < length; i++ ) {
912 // Create converters map
913 // with lowercased keys
915 for( key in s.converters ) {
916 if( typeof key === "string" ) {
917 converters[ key.toLowerCase() ] = s.converters[ key ];
924 current = dataTypes[ i ];
926 // If current is auto dataType, update it to prev
927 if( current === "*" ) {
929 // If no auto and dataTypes are actually different
930 } else if ( prev !== "*" && prev !== current ) {
933 conversion = prev + " " + current;
934 conv = converters[ conversion ] || converters[ "* " + current ];
936 // If there is no direct converter, search transitively
939 for( conv1 in converters ) {
940 tmp = conv1.split( " " );
941 if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
942 conv2 = converters[ tmp[1] + " " + current ];
944 conv1 = converters[ conv1 ];
945 if ( conv1 === true ) {
947 } else if ( conv2 === true ) {
955 // If we found no converter, dispatch an error
956 if ( !( conv || conv2 ) ) {
957 jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
959 // If found converter is not an equivalence
960 if ( conv !== true ) {
961 // Convert with 1 or 2 converters accordingly
962 response = conv ? conv( response ) : conv2( conv1(response) );