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, jXHR,
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, jXHR );
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, jXHR, 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, jXHR, "*", 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( jXHR, status, responseText ) {
159 // Store the response as specified by the jXHR object
160 responseText = jXHR.responseText;
161 // If successful, inject the HTML into all the matched elements
162 if ( jXHR.isResolved() ) {
163 // #4825: Get the actual response in case
164 // a dataFilter is present in ajaxSettings
165 jXHR.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, jXHR ] );
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 options is not an object,
326 // we simulate pre-1.5 signature
327 if ( typeof options !== "object" ) {
332 // Force options to be an object
333 options = options || {};
335 var // Create the final options object
336 s = jQuery.extend( true, {}, jQuery.ajaxSettings, options ),
338 // We force the original context if it exists
339 // or take it from jQuery.ajaxSettings otherwise
340 // (plain objects used as context get extended)
342 ( s.context = ( "context" in options ? options : jQuery.ajaxSettings ).context ) || s,
343 // Context for global events
344 // It's the callbackContext if one was provided in the options
345 // and if it's a DOM node
346 globalEventContext = callbackContext !== s && callbackContext.nodeType ?
347 jQuery( callbackContext ) : jQuery.event,
349 deferred = jQuery.Deferred(),
350 completeDeferred = jQuery._Deferred(),
351 // Status-dependent callbacks
352 statusCode = s.statusCode || {},
353 // Headers (they are sent all at once)
356 responseHeadersString,
362 // Cross-domain detection vars
363 loc = document.location,
364 protocol = loc.protocol || "http:",
376 setRequestHeader: function( name, value ) {
378 requestHeaders[ name.toLowerCase() ] = value;
384 getAllResponseHeaders: function() {
385 return state === 2 ? responseHeadersString : null;
388 // Builds headers hashtable if needed
389 getResponseHeader: function( key ) {
392 if ( !responseHeaders ) {
393 responseHeaders = {};
394 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
395 responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
398 match = responseHeaders[ key.toLowerCase() ];
400 return match || null;
403 // Cancel the request
404 abort: function( statusText ) {
405 statusText = statusText || "abort";
407 transport.abort( statusText );
409 done( 0, statusText );
414 // Callback for when everything is done
415 // It is defined here because jslint complains if it is declared
416 // at the end of the function (which would be more logical and readable)
417 function done( status, statusText, responses, headers) {
424 // State is "done" now
427 // Clear timeout if it exists
428 if ( timeoutTimer ) {
429 clearTimeout( timeoutTimer );
432 // Dereference transport for early garbage collection
433 // (no matter how long the jXHR object will be used)
434 transport = undefined;
436 // Cache response headers
437 responseHeadersString = headers || "";
440 jXHR.readyState = status ? 4 : 0;
445 response = responses ? ajaxHandleResponses( s, jXHR, responses ) : undefined,
449 // If successful, handle type chaining
450 if ( status >= 200 && status < 300 || status === 304 ) {
452 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
453 if ( s.ifModified ) {
455 if ( ( lastModified = jXHR.getResponseHeader( "Last-Modified" ) ) ) {
456 jQuery.lastModified[ s.url ] = lastModified;
458 if ( ( etag = jXHR.getResponseHeader( "Etag" ) ) ) {
459 jQuery.etag[ s.url ] = etag;
464 if ( status === 304 ) {
466 statusText = "notmodified";
473 success = ajaxConvert( s, response );
474 statusText = "success";
477 // We have a parsererror
478 statusText = "parsererror";
483 // We extract error from statusText
484 // then normalize statusText and status for non-aborts
487 statusText = "error";
494 // Set data for the fake xhr object
495 jXHR.status = status;
496 jXHR.statusText = statusText;
500 deferred.resolveWith( callbackContext, [ success, statusText, jXHR ] );
502 deferred.rejectWith( callbackContext, [ jXHR, statusText, error ] );
505 // Status-dependent callbacks
506 jXHR.statusCode( statusCode );
507 statusCode = undefined;
510 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
511 [ jXHR, s, isSuccess ? success : error ] );
515 completeDeferred.resolveWith( callbackContext, [ jXHR, statusText ] );
518 globalEventContext.trigger( "ajaxComplete", [ jXHR, s] );
519 // Handle the global AJAX counter
520 if ( !( --jQuery.active ) ) {
521 jQuery.event.trigger( "ajaxStop" );
527 deferred.promise( jXHR );
528 jXHR.success = jXHR.done;
529 jXHR.error = jXHR.fail;
530 jXHR.complete = completeDeferred.done;
532 // Status-dependent callbacks
533 jXHR.statusCode = function( map ) {
538 statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
541 tmp = map[ jXHR.status ];
542 jXHR.then( tmp, tmp );
548 // Remove hash character (#7531: and string promotion)
549 // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
550 // We also use the url parameter if available
551 s.url = ( "" + ( url || s.url ) ).replace( rhash, "" ).replace( rprotocol, protocol + "//" );
553 // Extract dataTypes list
554 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
556 // Determine if a cross-domain request is in order
557 if ( !s.crossDomain ) {
558 parts = rurl.exec( s.url.toLowerCase() );
559 s.crossDomain = !!( parts &&
560 ( parts[ 1 ] != protocol || parts[ 2 ] != loc.hostname ||
561 ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
562 ( loc.port || ( protocol === "http:" ? 80 : 443 ) ) )
566 // Convert data if not already a string
567 if ( s.data && s.processData && typeof s.data !== "string" ) {
568 s.data = jQuery.param( s.data, s.traditional );
572 inspectPrefiltersOrTransports( prefilters, s, options, jXHR );
574 // Uppercase the type
575 s.type = s.type.toUpperCase();
577 // Determine if request has content
578 s.hasContent = !rnoContent.test( s.type );
580 // Watch for a new set of requests
581 if ( s.global && jQuery.active++ === 0 ) {
582 jQuery.event.trigger( "ajaxStart" );
585 // More options handling for requests with no content
586 if ( !s.hasContent ) {
588 // If data is available, append data to url
590 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
593 // Add anti-cache in url if needed
594 if ( s.cache === false ) {
596 var ts = jQuery.now(),
597 // try replacing _= if it is there
598 ret = s.url.replace( rts, "$1_=" + ts );
600 // if nothing was replaced, add timestamp to the end
601 s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
605 // Set the correct header, if data is being sent
606 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
607 requestHeaders[ "content-type" ] = s.contentType;
610 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
611 if ( s.ifModified ) {
612 if ( jQuery.lastModified[ s.url ] ) {
613 requestHeaders[ "if-modified-since" ] = jQuery.lastModified[ s.url ];
615 if ( jQuery.etag[ s.url ] ) {
616 requestHeaders[ "if-none-match" ] = jQuery.etag[ s.url ];
620 // Set the Accepts header for the server, depending on the dataType
621 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
622 s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
625 // Check for headers option
626 for ( i in s.headers ) {
627 requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
630 // Allow custom headers/mimetypes and early abort
631 if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jXHR, s ) === false || state === 2 ) ) {
632 // Abort if not done already
639 // Install callbacks on deferreds
640 for ( i in { success: 1, error: 1, complete: 1 } ) {
645 transport = inspectPrefiltersOrTransports( transports, s, options, jXHR );
647 // If no transport, we auto-abort
649 done( -1, "No Transport" );
651 // Set state as sending
652 state = jXHR.readyState = 1;
655 globalEventContext.trigger( "ajaxSend", [ jXHR, s ] );
658 if ( s.async && s.timeout > 0 ) {
659 timeoutTimer = setTimeout( function(){
660 jXHR.abort( "timeout" );
665 transport.send( requestHeaders, done );
667 // Propagate exception as error if not done
670 // Simply rethrow otherwise
680 // Serialize an array of form elements or a set of
681 // key/values into a query string
682 param: function( a, traditional ) {
684 add = function( key, value ) {
685 // If value is a function, invoke it and return its value
686 value = jQuery.isFunction( value ) ? value() : value;
687 s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
690 // Set traditional to true for jQuery <= 1.3.2 behavior.
691 if ( traditional === undefined ) {
692 traditional = jQuery.ajaxSettings.traditional;
695 // If an array was passed in, assume that it is an array of form elements.
696 if ( jQuery.isArray( a ) || a.jquery ) {
697 // Serialize the form elements
698 jQuery.each( a, function() {
699 add( this.name, this.value );
703 // If traditional, encode the "old" way (the way 1.3.2 or older
704 // did it), otherwise encode params recursively.
705 for ( var prefix in a ) {
706 buildParams( prefix, a[ prefix ], traditional, add );
710 // Return the resulting serialization
711 return s.join( "&" ).replace( r20, "+" );
715 function buildParams( prefix, obj, traditional, add ) {
716 if ( jQuery.isArray( obj ) && obj.length ) {
717 // Serialize array item.
718 jQuery.each( obj, function( i, v ) {
719 if ( traditional || rbracket.test( prefix ) ) {
720 // Treat each array item as a scalar.
724 // If array item is non-scalar (array or object), encode its
725 // numeric index to resolve deserialization ambiguity issues.
726 // Note that rack (as of 1.0.0) can't currently deserialize
727 // nested arrays properly, and attempting to do so may cause
728 // a server error. Possible fixes are to modify rack's
729 // deserialization algorithm or to provide an option or flag
730 // to force array serialization to be shallow.
731 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
735 } else if ( !traditional && obj != null && typeof obj === "object" ) {
736 // If we see an array here, it is empty and should be treated as an empty
738 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
741 // Serialize object item.
743 for ( var name in obj ) {
744 buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
749 // Serialize scalar item.
754 // This is still on the jQuery object... for now
755 // Want to move this to jQuery.ajax some day
758 // Counter for holding the number of active queries
761 // Last-Modified header cache for next request
767 /* Handles responses to an ajax request:
768 * - sets all responseXXX fields accordingly
769 * - finds the right dataType (mediates between content-type and expected dataType)
770 * - returns the corresponding response
772 function ajaxHandleResponses( s, jXHR, responses ) {
774 var contents = s.contents,
775 dataTypes = s.dataTypes,
776 responseFields = s.responseFields,
782 // Fill responseXXX fields
783 for( type in responseFields ) {
784 if ( type in responses ) {
785 jXHR[ responseFields[type] ] = responses[ type ];
789 // Remove auto dataType and get content-type in the process
790 while( dataTypes[ 0 ] === "*" ) {
792 if ( ct === undefined ) {
793 ct = jXHR.getResponseHeader( "content-type" );
797 // Check if we're dealing with a known content-type
799 for ( type in contents ) {
800 if ( contents[ type ] && contents[ type ].test( ct ) ) {
801 dataTypes.unshift( type );
807 // Check to see if we have a response for the expected dataType
808 if ( dataTypes[ 0 ] in responses ) {
809 finalDataType = dataTypes[ 0 ];
811 // Try convertible dataTypes
812 for ( type in responses ) {
813 if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
814 finalDataType = type;
817 if ( !firstDataType ) {
818 firstDataType = type;
821 // Or just use first one
822 finalDataType = finalDataType || firstDataType;
825 // If we found a dataType
826 // We add the dataType to the list if needed
827 // and return the corresponding response
828 if ( finalDataType ) {
829 if ( finalDataType !== dataTypes[ 0 ] ) {
830 dataTypes.unshift( finalDataType );
832 return responses[ finalDataType ];
836 // Chain conversions given the request and the original response
837 function ajaxConvert( s, response ) {
839 // Apply the dataFilter if provided
840 if ( s.dataFilter ) {
841 response = s.dataFilter( response, s.dataType );
844 var dataTypes = s.dataTypes,
848 length = dataTypes.length,
850 // Current and previous dataTypes
851 current = dataTypes[ 0 ],
853 // Conversion expression
855 // Conversion function
857 // Conversion functions (transitive conversion)
861 // For each dataType in the chain
862 for( i = 1; i < length; i++ ) {
864 // Create converters map
865 // with lowercased keys
867 for( key in s.converters ) {
868 if( typeof key === "string" ) {
869 converters[ key.toLowerCase() ] = s.converters[ key ];
876 current = dataTypes[ i ];
878 // If current is auto dataType, update it to prev
879 if( current === "*" ) {
881 // If no auto and dataTypes are actually different
882 } else if ( prev !== "*" && prev !== current ) {
885 conversion = prev + " " + current;
886 conv = converters[ conversion ] || converters[ "* " + current ];
888 // If there is no direct converter, search transitively
891 for( conv1 in converters ) {
892 tmp = conv1.split( " " );
893 if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
894 conv2 = converters[ tmp[1] + " " + current ];
896 conv1 = converters[ conv1 ];
897 if ( conv1 === true ) {
899 } else if ( conv2 === true ) {
907 // If we found no converter, dispatch an error
908 if ( !( conv || conv2 ) ) {
909 jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
911 // If found converter is not an equivalence
912 if ( conv !== true ) {
913 // Convert with 1 or 2 converters accordingly
914 response = conv ? conv( response ) : conv2( conv1(response) );