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 rnoContent = /^(?:GET|HEAD)$/,
12 rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
13 rselectTextarea = /^(?:select|textarea)/i,
15 rts = /([?&])_=[^&]*/,
16 rurl = /^(\w+:)\/\/([^\/?#:]+)(?::(\d+))?/,
18 // Keep a copy of the old load method
19 _load = jQuery.fn.load,
22 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
23 * 2) These are called:
24 * - BEFORE asking for a transport
25 * - AFTER param serialization (s.data is a string if s.processData is true)
26 * 3) key is the dataType
27 * 4) the catchall symbol "*" can be used
28 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
32 /* Transports bindings
33 * 1) key is the dataType
34 * 2) the catchall symbol "*" can be used
35 * 3) selection will start with transport dataType and THEN go to "*" if needed
39 // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
40 function addToPrefiltersOrTransports( structure ) {
42 // dataTypeExpression is optional and defaults to "*"
43 return function( dataTypeExpression, func ) {
45 if ( typeof dataTypeExpression !== "string" ) {
46 func = dataTypeExpression;
47 dataTypeExpression = "*";
50 if ( jQuery.isFunction( func ) ) {
51 var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
53 length = dataTypes.length,
58 // For each dataType in the dataTypeExpression
59 for(; i < length; i++ ) {
60 dataType = dataTypes[ i ];
61 // We control if we're asked to add before
62 // any existing element
63 placeBefore = /^\+/.test( dataType );
65 dataType = dataType.substr( 1 ) || "*";
67 list = structure[ dataType ] = structure[ dataType ] || [];
68 // then we add to the structure accordingly
69 list[ placeBefore ? "unshift" : "push" ]( func );
75 //Base inspection function for prefilters and transports
76 function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
77 dataType /* internal */, inspected /* internal */ ) {
79 dataType = dataType || options.dataTypes[ 0 ];
80 inspected = inspected || {};
82 inspected[ dataType ] = true;
84 var list = structure[ dataType ],
86 length = list ? list.length : 0,
87 executeOnly = ( structure === prefilters ),
90 for(; i < length && ( executeOnly || !selection ); i++ ) {
91 selection = list[ i ]( options, originalOptions, jqXHR );
92 // If we got redirected to another dataType
93 // we try there if not done already
94 if ( typeof selection === "string" ) {
95 if ( inspected[ selection ] ) {
96 selection = undefined;
98 options.dataTypes.unshift( selection );
99 selection = inspectPrefiltersOrTransports(
100 structure, options, originalOptions, jqXHR, selection, inspected );
104 // If we're only executing or nothing was selected
105 // we try the catchall dataType if not done already
106 if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
107 selection = inspectPrefiltersOrTransports(
108 structure, options, originalOptions, jqXHR, "*", inspected );
110 // unnecessary when only executing (prefilters)
111 // but it'll be ignored by the caller in that case
116 load: function( url, params, callback ) {
117 if ( typeof url !== "string" && _load ) {
118 return _load.apply( this, arguments );
120 // Don't do a request if no elements are being requested
121 } else if ( !this.length ) {
125 var off = url.indexOf( " " );
127 var selector = url.slice( off, url.length );
128 url = url.slice( 0, off );
131 // Default to a GET request
134 // If the second parameter was provided
136 // If it's a function
137 if ( jQuery.isFunction( params ) ) {
138 // We assume that it's the callback
142 // Otherwise, build a param string
143 } else if ( typeof params === "object" ) {
144 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
151 // Request the remote document
157 // Complete callback (responseText is used internally)
158 complete: function( jqXHR, status, responseText ) {
159 // Store the response as specified by the jqXHR object
160 responseText = jqXHR.responseText;
161 // If successful, inject the HTML into all the matched elements
162 if ( jqXHR.isResolved() ) {
163 // #4825: Get the actual response in case
164 // a dataFilter is present in ajaxSettings
165 jqXHR.done(function( r ) {
168 // See if a selector was specified
169 self.html( selector ?
170 // Create a dummy div to hold the results
172 // inject the contents of the document in, removing the scripts
173 // to avoid any 'Permission Denied' errors in IE
174 .append(responseText.replace(rscript, ""))
176 // Locate the specified elements
179 // If not, just inject the full result
184 self.each( callback, [ responseText, status, jqXHR ] );
192 serialize: function() {
193 return jQuery.param( this.serializeArray() );
196 serializeArray: function() {
197 return this.map(function(){
198 return this.elements ? jQuery.makeArray( this.elements ) : this;
201 return this.name && !this.disabled &&
202 ( this.checked || rselectTextarea.test( this.nodeName ) ||
203 rinput.test( this.type ) );
205 .map(function( i, elem ){
206 var val = jQuery( this ).val();
210 jQuery.isArray( val ) ?
211 jQuery.map( val, function( val, i ){
212 return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
214 { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
219 // Attach a bunch of functions for handling common AJAX events
220 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
221 jQuery.fn[ o ] = function( f ){
222 return this.bind( o, f );
226 jQuery.each( [ "get", "post" ], function( i, method ) {
227 jQuery[ method ] = function( url, data, callback, type ) {
228 // shift arguments if data argument was omitted
229 if ( jQuery.isFunction( data ) ) {
230 type = type || callback;
247 getScript: function( url, callback ) {
248 return jQuery.get( url, null, callback, "script" );
251 getJSON: function( url, data, callback ) {
252 return jQuery.get( url, data, callback, "json" );
255 ajaxSetup: function( settings ) {
256 jQuery.extend( true, jQuery.ajaxSettings, settings );
257 if ( settings.context ) {
258 jQuery.ajaxSettings.context = settings.context;
266 contentType: "application/x-www-form-urlencoded",
282 xml: "application/xml, text/xml",
285 json: "application/json, text/javascript",
300 // List of data converters
301 // 1) key format is "source_type destination_type" (a single space in-between)
302 // 2) the catchall symbol "*" can be used for source_type
305 // Convert anything to text
306 "* text": window.String,
308 // Text to html (true = no transformation)
311 // Evaluate text as a json expression
312 "text json": jQuery.parseJSON,
315 "text xml": jQuery.parseXML
319 ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
320 ajaxTransport: addToPrefiltersOrTransports( transports ),
323 ajax: function( url, options ) {
325 // If url is an object, simulate pre-1.5 signature
326 if ( typeof url === "object" ) {
331 // Force options to be an object
332 options = options || {};
334 var // Create the final options object
335 s = jQuery.extend( true, {}, jQuery.ajaxSettings, options ),
337 // We force the original context if it exists
338 // or take it from jQuery.ajaxSettings otherwise
339 // (plain objects used as context get extended)
341 ( s.context = ( "context" in options ? options : jQuery.ajaxSettings ).context ) || s,
342 // Context for global events
343 // It's the callbackContext if one was provided in the options
344 // and if it's a DOM node
345 globalEventContext = callbackContext !== s && callbackContext.nodeType ?
346 jQuery( callbackContext ) : jQuery.event,
348 deferred = jQuery.Deferred(),
349 completeDeferred = jQuery._Deferred(),
350 // Status-dependent callbacks
351 statusCode = s.statusCode || {},
354 // Headers (they are sent all at once)
357 responseHeadersString,
363 // Cross-domain detection vars
364 loc = document.location,
365 protocol = loc.protocol || "http:",
377 setRequestHeader: function( name, value ) {
379 requestHeaders[ name.toLowerCase() ] = value;
385 getAllResponseHeaders: function() {
386 return state === 2 ? responseHeadersString : null;
389 // Builds headers hashtable if needed
390 getResponseHeader: function( key ) {
393 if ( !responseHeaders ) {
394 responseHeaders = {};
395 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
396 responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
399 match = responseHeaders[ key.toLowerCase() ];
401 return match || null;
404 // Cancel the request
405 abort: function( statusText ) {
406 statusText = statusText || "abort";
408 transport.abort( statusText );
410 done( 0, statusText );
415 // Callback for when everything is done
416 // It is defined here because jslint complains if it is declared
417 // at the end of the function (which would be more logical and readable)
418 function done( status, statusText, responses, headers) {
425 // State is "done" now
428 // Clear timeout if it exists
429 if ( timeoutTimer ) {
430 clearTimeout( timeoutTimer );
433 // Dereference transport for early garbage collection
434 // (no matter how long the jqXHR object will be used)
435 transport = undefined;
437 // Cache response headers
438 responseHeadersString = headers || "";
441 jqXHR.readyState = status ? 4 : 0;
446 response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
450 // If successful, handle type chaining
451 if ( status >= 200 && status < 300 || status === 304 ) {
453 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
454 if ( s.ifModified ) {
456 if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
457 jQuery.lastModified[ ifModifiedKey ] = lastModified;
459 if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
460 jQuery.etag[ ifModifiedKey ] = etag;
465 if ( status === 304 ) {
467 statusText = "notmodified";
474 success = ajaxConvert( s, response );
475 statusText = "success";
478 // We have a parsererror
479 statusText = "parsererror";
484 // We extract error from statusText
485 // then normalize statusText and status for non-aborts
488 statusText = "error";
495 // Set data for the fake xhr object
496 jqXHR.status = status;
497 jqXHR.statusText = statusText;
501 deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
503 deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
506 // Status-dependent callbacks
507 jqXHR.statusCode( statusCode );
508 statusCode = undefined;
511 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
512 [ jqXHR, s, isSuccess ? success : error ] );
516 completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );
519 globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] );
520 // Handle the global AJAX counter
521 if ( !( --jQuery.active ) ) {
522 jQuery.event.trigger( "ajaxStop" );
528 deferred.promise( jqXHR );
529 jqXHR.success = jqXHR.done;
530 jqXHR.error = jqXHR.fail;
531 jqXHR.complete = completeDeferred.done;
533 // Status-dependent callbacks
534 jqXHR.statusCode = function( map ) {
539 statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
542 tmp = map[ jqXHR.status ];
543 jqXHR.then( tmp, tmp );
549 // Remove hash character (#7531: and string promotion)
550 // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
551 // We also use the url parameter if available
552 s.url = ( "" + ( url || s.url ) ).replace( rhash, "" ).replace( rprotocol, protocol + "//" );
554 // Extract dataTypes list
555 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
557 // Determine if a cross-domain request is in order
558 if ( !s.crossDomain ) {
559 parts = rurl.exec( s.url.toLowerCase() );
560 s.crossDomain = !!( parts &&
561 ( parts[ 1 ] != protocol || parts[ 2 ] != loc.hostname ||
562 ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
563 ( loc.port || ( protocol === "http:" ? 80 : 443 ) ) )
567 // Convert data if not already a string
568 if ( s.data && s.processData && typeof s.data !== "string" ) {
569 s.data = jQuery.param( s.data, s.traditional );
573 inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
575 // Uppercase the type
576 s.type = s.type.toUpperCase();
578 // Determine if request has content
579 s.hasContent = !rnoContent.test( s.type );
581 // Watch for a new set of requests
582 if ( s.global && jQuery.active++ === 0 ) {
583 jQuery.event.trigger( "ajaxStart" );
586 // More options handling for requests with no content
587 if ( !s.hasContent ) {
589 // If data is available, append data to url
591 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
594 // Get ifModifiedKey before adding the anti-cache parameter
595 ifModifiedKey = s.url;
597 // Add anti-cache in url if needed
598 if ( s.cache === false ) {
600 var ts = jQuery.now(),
601 // try replacing _= if it is there
602 ret = s.url.replace( rts, "$1_=" + ts );
604 // if nothing was replaced, add timestamp to the end
605 s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
609 // Set the correct header, if data is being sent
610 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
611 requestHeaders[ "content-type" ] = s.contentType;
614 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
615 if ( s.ifModified ) {
616 ifModifiedKey = ifModifiedKey || s.url;
617 if ( jQuery.lastModified[ ifModifiedKey ] ) {
618 requestHeaders[ "if-modified-since" ] = jQuery.lastModified[ ifModifiedKey ];
620 if ( jQuery.etag[ ifModifiedKey ] ) {
621 requestHeaders[ "if-none-match" ] = jQuery.etag[ ifModifiedKey ];
625 // Set the Accepts header for the server, depending on the dataType
626 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
627 s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
630 // Check for headers option
631 for ( i in s.headers ) {
632 requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
635 // Allow custom headers/mimetypes and early abort
636 if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
637 // Abort if not done already
644 // Install callbacks on deferreds
645 for ( i in { success: 1, error: 1, complete: 1 } ) {
646 jqXHR[ i ]( s[ i ] );
650 transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
652 // If no transport, we auto-abort
654 done( -1, "No Transport" );
656 // Set state as sending
657 state = jqXHR.readyState = 1;
660 globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
663 if ( s.async && s.timeout > 0 ) {
664 timeoutTimer = setTimeout( function(){
665 jqXHR.abort( "timeout" );
670 transport.send( requestHeaders, done );
672 // Propagate exception as error if not done
675 // Simply rethrow otherwise
685 // Serialize an array of form elements or a set of
686 // key/values into a query string
687 param: function( a, traditional ) {
689 add = function( key, value ) {
690 // If value is a function, invoke it and return its value
691 value = jQuery.isFunction( value ) ? value() : value;
692 s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
695 // Set traditional to true for jQuery <= 1.3.2 behavior.
696 if ( traditional === undefined ) {
697 traditional = jQuery.ajaxSettings.traditional;
700 // If an array was passed in, assume that it is an array of form elements.
701 if ( jQuery.isArray( a ) || a.jquery ) {
702 // Serialize the form elements
703 jQuery.each( a, function() {
704 add( this.name, this.value );
708 // If traditional, encode the "old" way (the way 1.3.2 or older
709 // did it), otherwise encode params recursively.
710 for ( var prefix in a ) {
711 buildParams( prefix, a[ prefix ], traditional, add );
715 // Return the resulting serialization
716 return s.join( "&" ).replace( r20, "+" );
720 function buildParams( prefix, obj, traditional, add ) {
721 if ( jQuery.isArray( obj ) && obj.length ) {
722 // Serialize array item.
723 jQuery.each( obj, function( i, v ) {
724 if ( traditional || rbracket.test( prefix ) ) {
725 // Treat each array item as a scalar.
729 // If array item is non-scalar (array or object), encode its
730 // numeric index to resolve deserialization ambiguity issues.
731 // Note that rack (as of 1.0.0) can't currently deserialize
732 // nested arrays properly, and attempting to do so may cause
733 // a server error. Possible fixes are to modify rack's
734 // deserialization algorithm or to provide an option or flag
735 // to force array serialization to be shallow.
736 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
740 } else if ( !traditional && obj != null && typeof obj === "object" ) {
741 // If we see an array here, it is empty and should be treated as an empty
743 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
746 // Serialize object item.
748 for ( var name in obj ) {
749 buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
754 // Serialize scalar item.
759 // This is still on the jQuery object... for now
760 // Want to move this to jQuery.ajax some day
763 // Counter for holding the number of active queries
766 // Last-Modified header cache for next request
772 /* Handles responses to an ajax request:
773 * - sets all responseXXX fields accordingly
774 * - finds the right dataType (mediates between content-type and expected dataType)
775 * - returns the corresponding response
777 function ajaxHandleResponses( s, jqXHR, responses ) {
779 var contents = s.contents,
780 dataTypes = s.dataTypes,
781 responseFields = s.responseFields,
787 // Fill responseXXX fields
788 for( type in responseFields ) {
789 if ( type in responses ) {
790 jqXHR[ responseFields[type] ] = responses[ type ];
794 // Remove auto dataType and get content-type in the process
795 while( dataTypes[ 0 ] === "*" ) {
797 if ( ct === undefined ) {
798 ct = jqXHR.getResponseHeader( "content-type" );
802 // Check if we're dealing with a known content-type
804 for ( type in contents ) {
805 if ( contents[ type ] && contents[ type ].test( ct ) ) {
806 dataTypes.unshift( type );
812 // Check to see if we have a response for the expected dataType
813 if ( dataTypes[ 0 ] in responses ) {
814 finalDataType = dataTypes[ 0 ];
816 // Try convertible dataTypes
817 for ( type in responses ) {
818 if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
819 finalDataType = type;
822 if ( !firstDataType ) {
823 firstDataType = type;
826 // Or just use first one
827 finalDataType = finalDataType || firstDataType;
830 // If we found a dataType
831 // We add the dataType to the list if needed
832 // and return the corresponding response
833 if ( finalDataType ) {
834 if ( finalDataType !== dataTypes[ 0 ] ) {
835 dataTypes.unshift( finalDataType );
837 return responses[ finalDataType ];
841 // Chain conversions given the request and the original response
842 function ajaxConvert( s, response ) {
844 // Apply the dataFilter if provided
845 if ( s.dataFilter ) {
846 response = s.dataFilter( response, s.dataType );
849 var dataTypes = s.dataTypes,
853 length = dataTypes.length,
855 // Current and previous dataTypes
856 current = dataTypes[ 0 ],
858 // Conversion expression
860 // Conversion function
862 // Conversion functions (transitive conversion)
866 // For each dataType in the chain
867 for( i = 1; i < length; i++ ) {
869 // Create converters map
870 // with lowercased keys
872 for( key in s.converters ) {
873 if( typeof key === "string" ) {
874 converters[ key.toLowerCase() ] = s.converters[ key ];
881 current = dataTypes[ i ];
883 // If current is auto dataType, update it to prev
884 if( current === "*" ) {
886 // If no auto and dataTypes are actually different
887 } else if ( prev !== "*" && prev !== current ) {
890 conversion = prev + " " + current;
891 conv = converters[ conversion ] || converters[ "* " + current ];
893 // If there is no direct converter, search transitively
896 for( conv1 in converters ) {
897 tmp = conv1.split( " " );
898 if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
899 conv2 = converters[ tmp[1] + " " + current ];
901 conv1 = converters[ conv1 ];
902 if ( conv1 === true ) {
904 } else if ( conv2 === true ) {
912 // If we found no converter, dispatch an error
913 if ( !( conv || conv2 ) ) {
914 jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
916 // If found converter is not an equivalence
917 if ( conv !== true ) {
918 // Convert with 1 or 2 converters accordingly
919 response = conv ? conv( response ) : conv2( conv1(response) );