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 rurl = /^([\w\+\.\-]+:)\/\/([^\/?#:]*)(?::(\d+))?/,
20 // Keep a copy of the old load method
21 _load = jQuery.fn.load,
24 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
25 * 2) These are called:
26 * - BEFORE asking for a transport
27 * - AFTER param serialization (s.data is a string if s.processData is true)
28 * 3) key is the dataType
29 * 4) the catchall symbol "*" can be used
30 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
34 /* Transports bindings
35 * 1) key is the dataType
36 * 2) the catchall symbol "*" can be used
37 * 3) selection will start with transport dataType and THEN go to "*" if needed
44 // Document location segments
47 // #8138, IE may throw an exception when accessing
48 // a field from document.location if document.domain has been set
50 ajaxLocation = document.location.href;
52 // Use the href attribute of an A element
53 // since IE will modify it given document.location
54 ajaxLocation = document.createElement( "a" );
55 ajaxLocation.href = "";
56 ajaxLocation = ajaxLocation.href;
59 // Segment location into parts
60 ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() );
62 // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
63 function addToPrefiltersOrTransports( structure ) {
65 // dataTypeExpression is optional and defaults to "*"
66 return function( dataTypeExpression, func ) {
68 if ( typeof dataTypeExpression !== "string" ) {
69 func = dataTypeExpression;
70 dataTypeExpression = "*";
73 if ( jQuery.isFunction( func ) ) {
74 var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
76 length = dataTypes.length,
81 // For each dataType in the dataTypeExpression
82 for(; i < length; i++ ) {
83 dataType = dataTypes[ i ];
84 // We control if we're asked to add before
85 // any existing element
86 placeBefore = /^\+/.test( dataType );
88 dataType = dataType.substr( 1 ) || "*";
90 list = structure[ dataType ] = structure[ dataType ] || [];
91 // then we add to the structure accordingly
92 list[ placeBefore ? "unshift" : "push" ]( func );
98 //Base inspection function for prefilters and transports
99 function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
100 dataType /* internal */, inspected /* internal */ ) {
102 dataType = dataType || options.dataTypes[ 0 ];
103 inspected = inspected || {};
105 inspected[ dataType ] = true;
107 var list = structure[ dataType ],
109 length = list ? list.length : 0,
110 executeOnly = ( structure === prefilters ),
113 for(; i < length && ( executeOnly || !selection ); i++ ) {
114 selection = list[ i ]( options, originalOptions, jqXHR );
115 // If we got redirected to another dataType
116 // we try there if executing only and not done already
117 if ( typeof selection === "string" ) {
118 if ( !executeOnly || inspected[ selection ] ) {
119 selection = undefined;
121 options.dataTypes.unshift( selection );
122 selection = inspectPrefiltersOrTransports(
123 structure, options, originalOptions, jqXHR, selection, inspected );
127 // If we're only executing or nothing was selected
128 // we try the catchall dataType if not done already
129 if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
130 selection = inspectPrefiltersOrTransports(
131 structure, options, originalOptions, jqXHR, "*", inspected );
133 // unnecessary when only executing (prefilters)
134 // but it'll be ignored by the caller in that case
139 load: function( url, params, callback ) {
140 if ( typeof url !== "string" && _load ) {
141 return _load.apply( this, arguments );
143 // Don't do a request if no elements are being requested
144 } else if ( !this.length ) {
148 var off = url.indexOf( " " );
150 var selector = url.slice( off, url.length );
151 url = url.slice( 0, off );
154 // Default to a GET request
157 // If the second parameter was provided
159 // If it's a function
160 if ( jQuery.isFunction( params ) ) {
161 // We assume that it's the callback
165 // Otherwise, build a param string
166 } else if ( typeof params === "object" ) {
167 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
174 // Request the remote document
180 // Complete callback (responseText is used internally)
181 complete: function( jqXHR, status, responseText ) {
182 // Store the response as specified by the jqXHR object
183 responseText = jqXHR.responseText;
184 // If successful, inject the HTML into all the matched elements
185 if ( jqXHR.isResolved() ) {
186 // #4825: Get the actual response in case
187 // a dataFilter is present in ajaxSettings
188 jqXHR.done(function( r ) {
191 // See if a selector was specified
192 self.html( selector ?
193 // Create a dummy div to hold the results
195 // inject the contents of the document in, removing the scripts
196 // to avoid any 'Permission Denied' errors in IE
197 .append(responseText.replace(rscript, ""))
199 // Locate the specified elements
202 // If not, just inject the full result
207 self.each( callback, [ responseText, status, jqXHR ] );
215 serialize: function() {
216 return jQuery.param( this.serializeArray() );
219 serializeArray: function() {
220 return this.map(function(){
221 return this.elements ? jQuery.makeArray( this.elements ) : this;
224 return this.name && !this.disabled &&
225 ( this.checked || rselectTextarea.test( this.nodeName ) ||
226 rinput.test( this.type ) );
228 .map(function( i, elem ){
229 var val = jQuery( this ).val();
233 jQuery.isArray( val ) ?
234 jQuery.map( val, function( val, i ){
235 return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
237 { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
242 // Attach a bunch of functions for handling common AJAX events
243 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
244 jQuery.fn[ o ] = function( f ){
245 return this.bind( o, f );
249 jQuery.each( [ "get", "post" ], function( i, method ) {
250 jQuery[ method ] = function( url, data, callback, type ) {
251 // shift arguments if data argument was omitted
252 if ( jQuery.isFunction( data ) ) {
253 type = type || callback;
270 getScript: function( url, callback ) {
271 return jQuery.get( url, null, callback, "script" );
274 getJSON: function( url, data, callback ) {
275 return jQuery.get( url, data, callback, "json" );
278 ajaxSetup: function( settings ) {
279 jQuery.extend( true, jQuery.ajaxSettings, settings );
280 if ( settings.context ) {
281 jQuery.ajaxSettings.context = settings.context;
287 isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
290 contentType: "application/x-www-form-urlencoded",
306 xml: "application/xml, text/xml",
309 json: "application/json, text/javascript",
324 // List of data converters
325 // 1) key format is "source_type destination_type" (a single space in-between)
326 // 2) the catchall symbol "*" can be used for source_type
329 // Convert anything to text
330 "* text": window.String,
332 // Text to html (true = no transformation)
335 // Evaluate text as a json expression
336 "text json": jQuery.parseJSON,
339 "text xml": jQuery.parseXML
343 ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
344 ajaxTransport: addToPrefiltersOrTransports( transports ),
347 ajax: function( url, options ) {
349 // If url is an object, simulate pre-1.5 signature
350 if ( typeof url === "object" ) {
355 // Force options to be an object
356 options = options || {};
358 var // Create the final options object
359 s = jQuery.extend( true, {}, jQuery.ajaxSettings, options ),
361 // We force the original context if it exists
362 // or take it from jQuery.ajaxSettings otherwise
363 // (plain objects used as context get extended)
365 ( s.context = ( "context" in options ? options : jQuery.ajaxSettings ).context ) || s,
366 // Context for global events
367 // It's the callbackContext if one was provided in the options
368 // and if it's a DOM node
369 globalEventContext = callbackContext !== s && callbackContext.nodeType ?
370 jQuery( callbackContext ) : jQuery.event,
372 deferred = jQuery.Deferred(),
373 completeDeferred = jQuery._Deferred(),
374 // Status-dependent callbacks
375 statusCode = s.statusCode || {},
378 // Headers (they are sent all at once)
381 responseHeadersString,
387 // Cross-domain detection vars
391 // To know if global events are to be dispatched
401 setRequestHeader: function( name, value ) {
403 requestHeaders[ name.toLowerCase() ] = value;
409 getAllResponseHeaders: function() {
410 return state === 2 ? responseHeadersString : null;
413 // Builds headers hashtable if needed
414 getResponseHeader: function( key ) {
417 if ( !responseHeaders ) {
418 responseHeaders = {};
419 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
420 responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
423 match = responseHeaders[ key.toLowerCase() ];
425 return match || null;
428 // Cancel the request
429 abort: function( statusText ) {
430 statusText = statusText || "abort";
432 transport.abort( statusText );
434 done( 0, statusText );
439 // Callback for when everything is done
440 // It is defined here because jslint complains if it is declared
441 // at the end of the function (which would be more logical and readable)
442 function done( status, statusText, responses, headers) {
449 // State is "done" now
452 // Clear timeout if it exists
453 if ( timeoutTimer ) {
454 clearTimeout( timeoutTimer );
457 // Dereference transport for early garbage collection
458 // (no matter how long the jqXHR object will be used)
459 transport = undefined;
461 // Cache response headers
462 responseHeadersString = headers || "";
465 jqXHR.readyState = status ? 4 : 0;
470 response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
474 // If successful, handle type chaining
475 if ( status >= 200 && status < 300 || status === 304 ) {
477 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
478 if ( s.ifModified ) {
480 if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
481 jQuery.lastModified[ ifModifiedKey ] = lastModified;
483 if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
484 jQuery.etag[ ifModifiedKey ] = etag;
489 if ( status === 304 ) {
491 statusText = "notmodified";
498 success = ajaxConvert( s, response );
499 statusText = "success";
502 // We have a parsererror
503 statusText = "parsererror";
508 // We extract error from statusText
509 // then normalize statusText and status for non-aborts
512 statusText = "error";
519 // Set data for the fake xhr object
520 jqXHR.status = status;
521 jqXHR.statusText = statusText;
525 deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
527 deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
530 // Status-dependent callbacks
531 jqXHR.statusCode( statusCode );
532 statusCode = undefined;
535 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
536 [ jqXHR, s, isSuccess ? success : error ] );
540 completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );
543 globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] );
544 // Handle the global AJAX counter
545 if ( !( --jQuery.active ) ) {
546 jQuery.event.trigger( "ajaxStop" );
552 deferred.promise( jqXHR );
553 jqXHR.success = jqXHR.done;
554 jqXHR.error = jqXHR.fail;
555 jqXHR.complete = completeDeferred.done;
557 // Status-dependent callbacks
558 jqXHR.statusCode = function( map ) {
563 statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
566 tmp = map[ jqXHR.status ];
567 jqXHR.then( tmp, tmp );
573 // Remove hash character (#7531: and string promotion)
574 // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
575 // We also use the url parameter if available
576 s.url = ( "" + ( url || s.url ) ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
578 // Extract dataTypes list
579 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
581 // Determine if a cross-domain request is in order
582 if ( !s.crossDomain ) {
583 parts = rurl.exec( s.url.toLowerCase() );
584 s.crossDomain = !!( parts &&
585 ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
586 ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
587 ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
591 // Convert data if not already a string
592 if ( s.data && s.processData && typeof s.data !== "string" ) {
593 s.data = jQuery.param( s.data, s.traditional );
597 inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
599 // If request was aborted inside a prefiler, stop there
604 // We can fire global events as of now if asked to
605 fireGlobals = s.global;
607 // Uppercase the type
608 s.type = s.type.toUpperCase();
610 // Determine if request has content
611 s.hasContent = !rnoContent.test( s.type );
613 // Watch for a new set of requests
614 if ( fireGlobals && jQuery.active++ === 0 ) {
615 jQuery.event.trigger( "ajaxStart" );
618 // More options handling for requests with no content
619 if ( !s.hasContent ) {
621 // If data is available, append data to url
623 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
626 // Get ifModifiedKey before adding the anti-cache parameter
627 ifModifiedKey = s.url;
629 // Add anti-cache in url if needed
630 if ( s.cache === false ) {
632 var ts = jQuery.now(),
633 // try replacing _= if it is there
634 ret = s.url.replace( rts, "$1_=" + ts );
636 // if nothing was replaced, add timestamp to the end
637 s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
641 // Set the correct header, if data is being sent
642 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
643 requestHeaders[ "content-type" ] = s.contentType;
646 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
647 if ( s.ifModified ) {
648 ifModifiedKey = ifModifiedKey || s.url;
649 if ( jQuery.lastModified[ ifModifiedKey ] ) {
650 requestHeaders[ "if-modified-since" ] = jQuery.lastModified[ ifModifiedKey ];
652 if ( jQuery.etag[ ifModifiedKey ] ) {
653 requestHeaders[ "if-none-match" ] = jQuery.etag[ ifModifiedKey ];
657 // Set the Accepts header for the server, depending on the dataType
658 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
659 s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
662 // Check for headers option
663 for ( i in s.headers ) {
664 requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
667 // Allow custom headers/mimetypes and early abort
668 if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
669 // Abort if not done already
675 // Install callbacks on deferreds
676 for ( i in { success: 1, error: 1, complete: 1 } ) {
677 jqXHR[ i ]( s[ i ] );
681 transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
683 // If no transport, we auto-abort
685 done( -1, "No Transport" );
687 jqXHR.readyState = 1;
690 globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
693 if ( s.async && s.timeout > 0 ) {
694 timeoutTimer = setTimeout( function(){
695 jqXHR.abort( "timeout" );
701 transport.send( requestHeaders, done );
703 // Propagate exception as error if not done
706 // Simply rethrow otherwise
716 // Serialize an array of form elements or a set of
717 // key/values into a query string
718 param: function( a, traditional ) {
720 add = function( key, value ) {
721 // If value is a function, invoke it and return its value
722 value = jQuery.isFunction( value ) ? value() : value;
723 s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
726 // Set traditional to true for jQuery <= 1.3.2 behavior.
727 if ( traditional === undefined ) {
728 traditional = jQuery.ajaxSettings.traditional;
731 // If an array was passed in, assume that it is an array of form elements.
732 if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
733 // Serialize the form elements
734 jQuery.each( a, function() {
735 add( this.name, this.value );
739 // If traditional, encode the "old" way (the way 1.3.2 or older
740 // did it), otherwise encode params recursively.
741 for ( var prefix in a ) {
742 buildParams( prefix, a[ prefix ], traditional, add );
746 // Return the resulting serialization
747 return s.join( "&" ).replace( r20, "+" );
751 function buildParams( prefix, obj, traditional, add ) {
752 if ( jQuery.isArray( obj ) && obj.length ) {
753 // Serialize array item.
754 jQuery.each( obj, function( i, v ) {
755 if ( traditional || rbracket.test( prefix ) ) {
756 // Treat each array item as a scalar.
760 // If array item is non-scalar (array or object), encode its
761 // numeric index to resolve deserialization ambiguity issues.
762 // Note that rack (as of 1.0.0) can't currently deserialize
763 // nested arrays properly, and attempting to do so may cause
764 // a server error. Possible fixes are to modify rack's
765 // deserialization algorithm or to provide an option or flag
766 // to force array serialization to be shallow.
767 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
771 } else if ( !traditional && obj != null && typeof obj === "object" ) {
772 // If we see an array here, it is empty and should be treated as an empty
774 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
777 // Serialize object item.
779 for ( var name in obj ) {
780 buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
785 // Serialize scalar item.
790 // This is still on the jQuery object... for now
791 // Want to move this to jQuery.ajax some day
794 // Counter for holding the number of active queries
797 // Last-Modified header cache for next request
803 /* Handles responses to an ajax request:
804 * - sets all responseXXX fields accordingly
805 * - finds the right dataType (mediates between content-type and expected dataType)
806 * - returns the corresponding response
808 function ajaxHandleResponses( s, jqXHR, responses ) {
810 var contents = s.contents,
811 dataTypes = s.dataTypes,
812 responseFields = s.responseFields,
818 // Fill responseXXX fields
819 for( type in responseFields ) {
820 if ( type in responses ) {
821 jqXHR[ responseFields[type] ] = responses[ type ];
825 // Remove auto dataType and get content-type in the process
826 while( dataTypes[ 0 ] === "*" ) {
828 if ( ct === undefined ) {
829 ct = jqXHR.getResponseHeader( "content-type" );
833 // Check if we're dealing with a known content-type
835 for ( type in contents ) {
836 if ( contents[ type ] && contents[ type ].test( ct ) ) {
837 dataTypes.unshift( type );
843 // Check to see if we have a response for the expected dataType
844 if ( dataTypes[ 0 ] in responses ) {
845 finalDataType = dataTypes[ 0 ];
847 // Try convertible dataTypes
848 for ( type in responses ) {
849 if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
850 finalDataType = type;
853 if ( !firstDataType ) {
854 firstDataType = type;
857 // Or just use first one
858 finalDataType = finalDataType || firstDataType;
861 // If we found a dataType
862 // We add the dataType to the list if needed
863 // and return the corresponding response
864 if ( finalDataType ) {
865 if ( finalDataType !== dataTypes[ 0 ] ) {
866 dataTypes.unshift( finalDataType );
868 return responses[ finalDataType ];
872 // Chain conversions given the request and the original response
873 function ajaxConvert( s, response ) {
875 // Apply the dataFilter if provided
876 if ( s.dataFilter ) {
877 response = s.dataFilter( response, s.dataType );
880 var dataTypes = s.dataTypes,
884 length = dataTypes.length,
886 // Current and previous dataTypes
887 current = dataTypes[ 0 ],
889 // Conversion expression
891 // Conversion function
893 // Conversion functions (transitive conversion)
897 // For each dataType in the chain
898 for( i = 1; i < length; i++ ) {
900 // Create converters map
901 // with lowercased keys
903 for( key in s.converters ) {
904 if( typeof key === "string" ) {
905 converters[ key.toLowerCase() ] = s.converters[ key ];
912 current = dataTypes[ i ];
914 // If current is auto dataType, update it to prev
915 if( current === "*" ) {
917 // If no auto and dataTypes are actually different
918 } else if ( prev !== "*" && prev !== current ) {
921 conversion = prev + " " + current;
922 conv = converters[ conversion ] || converters[ "* " + current ];
924 // If there is no direct converter, search transitively
927 for( conv1 in converters ) {
928 tmp = conv1.split( " " );
929 if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
930 conv2 = converters[ tmp[1] + " " + current ];
932 conv1 = converters[ conv1 ];
933 if ( conv1 === true ) {
935 } else if ( conv2 === true ) {
943 // If we found no converter, dispatch an error
944 if ( !( conv || conv2 ) ) {
945 jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
947 // If found converter is not an equivalence
948 if ( conv !== true ) {
949 // Convert with 1 or 2 converters accordingly
950 response = conv ? conv( response ) : conv2( conv1(response) );