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 // Stored document location array
42 // #8138, IE may throw an exception when accessing
43 // a field from document.location if document.domain has been set
45 ajaxLocation = document.location.href;
47 // Use the href attribute of an A element
48 // since IE will modify it given document.location
49 ajaxLocation = document.createElement( "a" );
50 ajaxLocation.href = "";
51 ajaxLocation = ajaxLocation.href;
54 // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
55 function addToPrefiltersOrTransports( structure ) {
57 // dataTypeExpression is optional and defaults to "*"
58 return function( dataTypeExpression, func ) {
60 if ( typeof dataTypeExpression !== "string" ) {
61 func = dataTypeExpression;
62 dataTypeExpression = "*";
65 if ( jQuery.isFunction( func ) ) {
66 var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
68 length = dataTypes.length,
73 // For each dataType in the dataTypeExpression
74 for(; i < length; i++ ) {
75 dataType = dataTypes[ i ];
76 // We control if we're asked to add before
77 // any existing element
78 placeBefore = /^\+/.test( dataType );
80 dataType = dataType.substr( 1 ) || "*";
82 list = structure[ dataType ] = structure[ dataType ] || [];
83 // then we add to the structure accordingly
84 list[ placeBefore ? "unshift" : "push" ]( func );
90 //Base inspection function for prefilters and transports
91 function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
92 dataType /* internal */, inspected /* internal */ ) {
94 dataType = dataType || options.dataTypes[ 0 ];
95 inspected = inspected || {};
97 inspected[ dataType ] = true;
99 var list = structure[ dataType ],
101 length = list ? list.length : 0,
102 executeOnly = ( structure === prefilters ),
105 for(; i < length && ( executeOnly || !selection ); i++ ) {
106 selection = list[ i ]( options, originalOptions, jqXHR );
107 // If we got redirected to another dataType
108 // we try there if not done already
109 if ( typeof selection === "string" ) {
110 if ( inspected[ selection ] ) {
111 selection = undefined;
113 options.dataTypes.unshift( selection );
114 selection = inspectPrefiltersOrTransports(
115 structure, options, originalOptions, jqXHR, selection, inspected );
119 // If we're only executing or nothing was selected
120 // we try the catchall dataType if not done already
121 if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
122 selection = inspectPrefiltersOrTransports(
123 structure, options, originalOptions, jqXHR, "*", inspected );
125 // unnecessary when only executing (prefilters)
126 // but it'll be ignored by the caller in that case
131 load: function( url, params, callback ) {
132 if ( typeof url !== "string" && _load ) {
133 return _load.apply( this, arguments );
135 // Don't do a request if no elements are being requested
136 } else if ( !this.length ) {
140 var off = url.indexOf( " " );
142 var selector = url.slice( off, url.length );
143 url = url.slice( 0, off );
146 // Default to a GET request
149 // If the second parameter was provided
151 // If it's a function
152 if ( jQuery.isFunction( params ) ) {
153 // We assume that it's the callback
157 // Otherwise, build a param string
158 } else if ( typeof params === "object" ) {
159 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
166 // Request the remote document
172 // Complete callback (responseText is used internally)
173 complete: function( jqXHR, status, responseText ) {
174 // Store the response as specified by the jqXHR object
175 responseText = jqXHR.responseText;
176 // If successful, inject the HTML into all the matched elements
177 if ( jqXHR.isResolved() ) {
178 // #4825: Get the actual response in case
179 // a dataFilter is present in ajaxSettings
180 jqXHR.done(function( r ) {
183 // See if a selector was specified
184 self.html( selector ?
185 // Create a dummy div to hold the results
187 // inject the contents of the document in, removing the scripts
188 // to avoid any 'Permission Denied' errors in IE
189 .append(responseText.replace(rscript, ""))
191 // Locate the specified elements
194 // If not, just inject the full result
199 self.each( callback, [ responseText, status, jqXHR ] );
207 serialize: function() {
208 return jQuery.param( this.serializeArray() );
211 serializeArray: function() {
212 return this.map(function(){
213 return this.elements ? jQuery.makeArray( this.elements ) : this;
216 return this.name && !this.disabled &&
217 ( this.checked || rselectTextarea.test( this.nodeName ) ||
218 rinput.test( this.type ) );
220 .map(function( i, elem ){
221 var val = jQuery( this ).val();
225 jQuery.isArray( val ) ?
226 jQuery.map( val, function( val, i ){
227 return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
229 { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
234 // Attach a bunch of functions for handling common AJAX events
235 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
236 jQuery.fn[ o ] = function( f ){
237 return this.bind( o, f );
241 jQuery.each( [ "get", "post" ], function( i, method ) {
242 jQuery[ method ] = function( url, data, callback, type ) {
243 // shift arguments if data argument was omitted
244 if ( jQuery.isFunction( data ) ) {
245 type = type || callback;
262 getScript: function( url, callback ) {
263 return jQuery.get( url, null, callback, "script" );
266 getJSON: function( url, data, callback ) {
267 return jQuery.get( url, data, callback, "json" );
270 ajaxSetup: function( settings ) {
271 jQuery.extend( true, jQuery.ajaxSettings, settings );
272 if ( settings.context ) {
273 jQuery.ajaxSettings.context = settings.context;
281 contentType: "application/x-www-form-urlencoded",
297 xml: "application/xml, text/xml",
300 json: "application/json, text/javascript",
315 // List of data converters
316 // 1) key format is "source_type destination_type" (a single space in-between)
317 // 2) the catchall symbol "*" can be used for source_type
320 // Convert anything to text
321 "* text": window.String,
323 // Text to html (true = no transformation)
326 // Evaluate text as a json expression
327 "text json": jQuery.parseJSON,
330 "text xml": jQuery.parseXML
334 ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
335 ajaxTransport: addToPrefiltersOrTransports( transports ),
338 ajax: function( url, options ) {
340 // If url is an object, simulate pre-1.5 signature
341 if ( typeof url === "object" ) {
346 // Force options to be an object
347 options = options || {};
349 var // Create the final options object
350 s = jQuery.extend( true, {}, jQuery.ajaxSettings, options ),
352 // We force the original context if it exists
353 // or take it from jQuery.ajaxSettings otherwise
354 // (plain objects used as context get extended)
356 ( s.context = ( "context" in options ? options : jQuery.ajaxSettings ).context ) || s,
357 // Context for global events
358 // It's the callbackContext if one was provided in the options
359 // and if it's a DOM node
360 globalEventContext = callbackContext !== s && callbackContext.nodeType ?
361 jQuery( callbackContext ) : jQuery.event,
363 deferred = jQuery.Deferred(),
364 completeDeferred = jQuery._Deferred(),
365 // Status-dependent callbacks
366 statusCode = s.statusCode || {},
369 // Headers (they are sent all at once)
372 responseHeadersString,
378 // Cross-domain detection vars
390 setRequestHeader: function( name, value ) {
392 requestHeaders[ name.toLowerCase() ] = value;
398 getAllResponseHeaders: function() {
399 return state === 2 ? responseHeadersString : null;
402 // Builds headers hashtable if needed
403 getResponseHeader: function( key ) {
406 if ( !responseHeaders ) {
407 responseHeaders = {};
408 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
409 responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
412 match = responseHeaders[ key.toLowerCase() ];
414 return match || null;
417 // Cancel the request
418 abort: function( statusText ) {
419 statusText = statusText || "abort";
421 transport.abort( statusText );
423 done( 0, statusText );
428 // Callback for when everything is done
429 // It is defined here because jslint complains if it is declared
430 // at the end of the function (which would be more logical and readable)
431 function done( status, statusText, responses, headers) {
438 // State is "done" now
441 // Clear timeout if it exists
442 if ( timeoutTimer ) {
443 clearTimeout( timeoutTimer );
446 // Dereference transport for early garbage collection
447 // (no matter how long the jqXHR object will be used)
448 transport = undefined;
450 // Cache response headers
451 responseHeadersString = headers || "";
454 jqXHR.readyState = status ? 4 : 0;
459 response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
463 // If successful, handle type chaining
464 if ( status >= 200 && status < 300 || status === 304 ) {
466 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
467 if ( s.ifModified ) {
469 if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
470 jQuery.lastModified[ ifModifiedKey ] = lastModified;
472 if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
473 jQuery.etag[ ifModifiedKey ] = etag;
478 if ( status === 304 ) {
480 statusText = "notmodified";
487 success = ajaxConvert( s, response );
488 statusText = "success";
491 // We have a parsererror
492 statusText = "parsererror";
497 // We extract error from statusText
498 // then normalize statusText and status for non-aborts
501 statusText = "error";
508 // Set data for the fake xhr object
509 jqXHR.status = status;
510 jqXHR.statusText = statusText;
514 deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
516 deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
519 // Status-dependent callbacks
520 jqXHR.statusCode( statusCode );
521 statusCode = undefined;
524 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
525 [ jqXHR, s, isSuccess ? success : error ] );
529 completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );
532 globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] );
533 // Handle the global AJAX counter
534 if ( !( --jQuery.active ) ) {
535 jQuery.event.trigger( "ajaxStop" );
541 deferred.promise( jqXHR );
542 jqXHR.success = jqXHR.done;
543 jqXHR.error = jqXHR.fail;
544 jqXHR.complete = completeDeferred.done;
546 // Status-dependent callbacks
547 jqXHR.statusCode = function( map ) {
552 statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
555 tmp = map[ jqXHR.status ];
556 jqXHR.then( tmp, tmp );
562 // Remove hash character (#7531: and string promotion)
563 // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
564 // We also use the url parameter if available
565 s.url = ( "" + ( url || s.url ) ).replace( rhash, "" ).replace( rprotocol, ajaxLocation[ 1 ] + "//" );
567 // Extract dataTypes list
568 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
570 // Determine if a cross-domain request is in order
571 if ( !s.crossDomain ) {
572 parts = rurl.exec( s.url.toLowerCase() );
573 s.crossDomain = !!( parts &&
574 ( parts[ 1 ] != ajaxLocation[ 1 ] || parts[ 2 ] != ajaxLocation[ 2 ] ||
575 ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
576 ( ajaxLocation[ 3 ] || ( ajaxLocation[ 1 ] === "http:" ? 80 : 443 ) ) )
580 // Convert data if not already a string
581 if ( s.data && s.processData && typeof s.data !== "string" ) {
582 s.data = jQuery.param( s.data, s.traditional );
586 inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
588 // Uppercase the type
589 s.type = s.type.toUpperCase();
591 // Determine if request has content
592 s.hasContent = !rnoContent.test( s.type );
594 // Watch for a new set of requests
595 if ( s.global && jQuery.active++ === 0 ) {
596 jQuery.event.trigger( "ajaxStart" );
599 // More options handling for requests with no content
600 if ( !s.hasContent ) {
602 // If data is available, append data to url
604 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
607 // Get ifModifiedKey before adding the anti-cache parameter
608 ifModifiedKey = s.url;
610 // Add anti-cache in url if needed
611 if ( s.cache === false ) {
613 var ts = jQuery.now(),
614 // try replacing _= if it is there
615 ret = s.url.replace( rts, "$1_=" + ts );
617 // if nothing was replaced, add timestamp to the end
618 s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
622 // Set the correct header, if data is being sent
623 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
624 requestHeaders[ "content-type" ] = s.contentType;
627 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
628 if ( s.ifModified ) {
629 ifModifiedKey = ifModifiedKey || s.url;
630 if ( jQuery.lastModified[ ifModifiedKey ] ) {
631 requestHeaders[ "if-modified-since" ] = jQuery.lastModified[ ifModifiedKey ];
633 if ( jQuery.etag[ ifModifiedKey ] ) {
634 requestHeaders[ "if-none-match" ] = jQuery.etag[ ifModifiedKey ];
638 // Set the Accepts header for the server, depending on the dataType
639 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
640 s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
643 // Check for headers option
644 for ( i in s.headers ) {
645 requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
648 // Allow custom headers/mimetypes and early abort
649 if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
650 // Abort if not done already
657 // Install callbacks on deferreds
658 for ( i in { success: 1, error: 1, complete: 1 } ) {
659 jqXHR[ i ]( s[ i ] );
663 transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
665 // If no transport, we auto-abort
667 done( -1, "No Transport" );
669 // Set state as sending
670 state = jqXHR.readyState = 1;
673 globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
676 if ( s.async && s.timeout > 0 ) {
677 timeoutTimer = setTimeout( function(){
678 jqXHR.abort( "timeout" );
683 transport.send( requestHeaders, done );
685 // Propagate exception as error if not done
688 // Simply rethrow otherwise
698 // Serialize an array of form elements or a set of
699 // key/values into a query string
700 param: function( a, traditional ) {
702 add = function( key, value ) {
703 // If value is a function, invoke it and return its value
704 value = jQuery.isFunction( value ) ? value() : value;
705 s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
708 // Set traditional to true for jQuery <= 1.3.2 behavior.
709 if ( traditional === undefined ) {
710 traditional = jQuery.ajaxSettings.traditional;
713 // If an array was passed in, assume that it is an array of form elements.
714 if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
715 // Serialize the form elements
716 jQuery.each( a, function() {
717 add( this.name, this.value );
721 // If traditional, encode the "old" way (the way 1.3.2 or older
722 // did it), otherwise encode params recursively.
723 for ( var prefix in a ) {
724 buildParams( prefix, a[ prefix ], traditional, add );
728 // Return the resulting serialization
729 return s.join( "&" ).replace( r20, "+" );
733 // Segment ajaxLocation into parts
734 ajaxLocation = rurl.exec( ajaxLocation.toLowerCase() );
736 function buildParams( prefix, obj, traditional, add ) {
737 if ( jQuery.isArray( obj ) && obj.length ) {
738 // Serialize array item.
739 jQuery.each( obj, function( i, v ) {
740 if ( traditional || rbracket.test( prefix ) ) {
741 // Treat each array item as a scalar.
745 // If array item is non-scalar (array or object), encode its
746 // numeric index to resolve deserialization ambiguity issues.
747 // Note that rack (as of 1.0.0) can't currently deserialize
748 // nested arrays properly, and attempting to do so may cause
749 // a server error. Possible fixes are to modify rack's
750 // deserialization algorithm or to provide an option or flag
751 // to force array serialization to be shallow.
752 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
756 } else if ( !traditional && obj != null && typeof obj === "object" ) {
757 // If we see an array here, it is empty and should be treated as an empty
759 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
762 // Serialize object item.
764 for ( var name in obj ) {
765 buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
770 // Serialize scalar item.
775 // This is still on the jQuery object... for now
776 // Want to move this to jQuery.ajax some day
779 // Counter for holding the number of active queries
782 // Last-Modified header cache for next request
788 /* Handles responses to an ajax request:
789 * - sets all responseXXX fields accordingly
790 * - finds the right dataType (mediates between content-type and expected dataType)
791 * - returns the corresponding response
793 function ajaxHandleResponses( s, jqXHR, responses ) {
795 var contents = s.contents,
796 dataTypes = s.dataTypes,
797 responseFields = s.responseFields,
803 // Fill responseXXX fields
804 for( type in responseFields ) {
805 if ( type in responses ) {
806 jqXHR[ responseFields[type] ] = responses[ type ];
810 // Remove auto dataType and get content-type in the process
811 while( dataTypes[ 0 ] === "*" ) {
813 if ( ct === undefined ) {
814 ct = jqXHR.getResponseHeader( "content-type" );
818 // Check if we're dealing with a known content-type
820 for ( type in contents ) {
821 if ( contents[ type ] && contents[ type ].test( ct ) ) {
822 dataTypes.unshift( type );
828 // Check to see if we have a response for the expected dataType
829 if ( dataTypes[ 0 ] in responses ) {
830 finalDataType = dataTypes[ 0 ];
832 // Try convertible dataTypes
833 for ( type in responses ) {
834 if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
835 finalDataType = type;
838 if ( !firstDataType ) {
839 firstDataType = type;
842 // Or just use first one
843 finalDataType = finalDataType || firstDataType;
846 // If we found a dataType
847 // We add the dataType to the list if needed
848 // and return the corresponding response
849 if ( finalDataType ) {
850 if ( finalDataType !== dataTypes[ 0 ] ) {
851 dataTypes.unshift( finalDataType );
853 return responses[ finalDataType ];
857 // Chain conversions given the request and the original response
858 function ajaxConvert( s, response ) {
860 // Apply the dataFilter if provided
861 if ( s.dataFilter ) {
862 response = s.dataFilter( response, s.dataType );
865 var dataTypes = s.dataTypes,
869 length = dataTypes.length,
871 // Current and previous dataTypes
872 current = dataTypes[ 0 ],
874 // Conversion expression
876 // Conversion function
878 // Conversion functions (transitive conversion)
882 // For each dataType in the chain
883 for( i = 1; i < length; i++ ) {
885 // Create converters map
886 // with lowercased keys
888 for( key in s.converters ) {
889 if( typeof key === "string" ) {
890 converters[ key.toLowerCase() ] = s.converters[ key ];
897 current = dataTypes[ i ];
899 // If current is auto dataType, update it to prev
900 if( current === "*" ) {
902 // If no auto and dataTypes are actually different
903 } else if ( prev !== "*" && prev !== current ) {
906 conversion = prev + " " + current;
907 conv = converters[ conversion ] || converters[ "* " + current ];
909 // If there is no direct converter, search transitively
912 for( conv1 in converters ) {
913 tmp = conv1.split( " " );
914 if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
915 conv2 = converters[ tmp[1] + " " + current ];
917 conv1 = converters[ conv1 ];
918 if ( conv1 === true ) {
920 } else if ( conv2 === true ) {
928 // If we found no converter, dispatch an error
929 if ( !( conv || conv2 ) ) {
930 jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
932 // If found converter is not an equivalence
933 if ( conv !== true ) {
934 // Convert with 1 or 2 converters accordingly
935 response = conv ? conv( response ) : conv2( conv1(response) );