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)$/,
11 rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
12 rselectTextarea = /^(?:select|textarea)/i,
14 rts = /([?&])_=[^&]*/,
15 rurl = /^(\w+:)?\/\/([^\/?#:]+)(?::(\d+))?/,
18 sliceFunc = Array.prototype.slice,
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
41 // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
42 function addToPrefiltersOrTransports( structure ) {
44 // dataTypeExpression is optional and defaults to "*"
45 return function( dataTypeExpression, func ) {
47 if ( typeof dataTypeExpression !== "string" ) {
48 func = dataTypeExpression;
49 dataTypeExpression = "*";
52 if ( jQuery.isFunction( func ) ) {
53 var dataTypes = dataTypeExpression.split( rspacesAjax ),
55 length = dataTypes.length,
60 // For each dataType in the dataTypeExpression
61 for(; i < length; i++ ) {
62 dataType = dataTypes[ i ];
63 // We control if we're asked to add before
64 // any existing element
65 placeBefore = /^\+/.test( dataType );
67 dataType = dataType.substr( 1 );
69 list = structure[ dataType ] = structure[ dataType ] || [];
70 // then we add to the structure accordingly
71 list[ placeBefore ? "unshift" : "push" ]( func );
77 //Base inspection function for prefilters and transports
78 function inspectPrefiltersOrTransports( structure, options, originalOptions,
79 dataType /* internal */, inspected /* internal */ ) {
81 dataType = dataType || options.dataTypes[ 0 ];
82 inspected = inspected || {};
84 inspected[ dataType ] = true;
86 var list = structure[ dataType ],
88 length = list ? list.length : 0,
89 executeOnly = ( structure === prefilters ),
92 for(; i < length && ( executeOnly || !selection ); i++ ) {
93 selection = list[ i ]( options, originalOptions );
94 // If we got redirected to another dataType
95 // we try there if not done already
96 if ( typeof selection === "string" ) {
97 if ( inspected[ selection ] ) {
98 selection = undefined;
100 options.dataTypes.unshift( selection );
101 selection = inspectPrefiltersOrTransports(
102 structure, options, originalOptions, selection, inspected );
106 // If we're only executing or nothing was selected
107 // we try the catchall dataType if not done already
108 if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
109 selection = inspectPrefiltersOrTransports(
110 structure, options, originalOptions, "*", inspected );
112 // unnecessary when only executing (prefilters)
113 // but it'll be ignored by the caller in that case
118 load: function( url, params, callback ) {
119 if ( typeof url !== "string" && _load ) {
120 return _load.apply( this, arguments );
122 // Don't do a request if no elements are being requested
123 } else if ( !this.length ) {
127 var off = url.indexOf( " " );
129 var selector = url.slice( off, url.length );
130 url = url.slice( 0, off );
133 // Default to a GET request
136 // If the second parameter was provided
138 // If it's a function
139 if ( jQuery.isFunction( params ) ) {
140 // We assume that it's the callback
144 // Otherwise, build a param string
145 } else if ( typeof params === "object" ) {
146 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
153 // Request the remote document
159 // Complete callback (responseText is used internally)
160 complete: function( jXHR, status, responseText ) {
161 // Store the response as specified by the jXHR object
162 responseText = jXHR.responseText;
163 // If successful, inject the HTML into all the matched elements
164 if ( jXHR.isResolved() ) {
165 // #4825: Get the actual response in case
166 // a dataFilter is present in ajaxSettings
167 jXHR.done(function( r ) {
170 // See if a selector was specified
171 self.html( selector ?
172 // Create a dummy div to hold the results
174 // inject the contents of the document in, removing the scripts
175 // to avoid any 'Permission Denied' errors in IE
176 .append(responseText.replace(rscript, ""))
178 // Locate the specified elements
181 // If not, just inject the full result
186 self.each( callback, [ responseText, status, jXHR ] );
194 serialize: function() {
195 return jQuery.param( this.serializeArray() );
198 serializeArray: function() {
199 return this.map(function(){
200 return this.elements ? jQuery.makeArray( this.elements ) : this;
203 return this.name && !this.disabled &&
204 ( this.checked || rselectTextarea.test( this.nodeName ) ||
205 rinput.test( this.type ) );
207 .map(function( i, elem ){
208 var val = jQuery( this ).val();
212 jQuery.isArray( val ) ?
213 jQuery.map( val, function( val, i ){
214 return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
216 { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
221 // Attach a bunch of functions for handling common AJAX events
222 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
223 jQuery.fn[ o ] = function( f ){
224 return this.bind( o, f );
228 jQuery.each( [ "get", "post" ], function( i, method ) {
229 jQuery[ method ] = function( url, data, callback, type ) {
230 // shift arguments if data argument was omitted
231 if ( jQuery.isFunction( data ) ) {
232 type = type || callback;
249 getScript: function( url, callback ) {
250 return jQuery.get( url, null, callback, "script" );
253 getJSON: function( url, data, callback ) {
254 return jQuery.get( url, data, callback, "json" );
257 ajaxSetup: function( settings ) {
258 jQuery.extend( true, jQuery.ajaxSettings, settings );
259 if ( settings.context ) {
260 jQuery.ajaxSettings.context = settings.context;
268 contentType: "application/x-www-form-urlencoded",
284 xml: "application/xml, text/xml",
287 json: "application/json, text/javascript",
302 // List of data converters
303 // 1) key format is "source_type destination_type" (a single space in-between)
304 // 2) the catchall symbol "*" can be used for source_type
307 // Convert anything to text
308 "* text": window.String,
310 // Text to html (true = no transformation)
313 // Evaluate text as a json expression
314 "text json": jQuery.parseJSON,
317 "text xml": jQuery.parseXML
321 ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
322 ajaxTransport: addToPrefiltersOrTransports( transports ),
325 ajax: function( url, options ) {
327 // If options is not an object,
328 // we simulate pre-1.5 signature
329 if ( typeof options !== "object" ) {
334 // Force options to be an object
335 options = options || {};
337 var // Create the final options object
338 s = jQuery.extend( true, {}, jQuery.ajaxSettings, options ),
339 // Callbacks contexts
340 // We force the original context if it exists
341 // or take it from jQuery.ajaxSettings otherwise
342 // (plain objects used as context get extended)
344 ( s.context = ( "context" in options ? options : jQuery.ajaxSettings ).context ) || s,
345 globalEventContext = callbackContext === s ? jQuery.event : jQuery( callbackContext ),
347 deferred = jQuery.Deferred(),
348 completeDeferred = jQuery._Deferred(),
349 // Status-dependent callbacks
350 statusCode = s.statusCode || {},
351 // Headers (they are sent all at once)
354 responseHeadersString,
360 // Cross-domain detection vars
361 loc = document.location,
362 protocol = loc.protocol || "http:",
374 setRequestHeader: function( name, value ) {
376 requestHeaders[ name.toLowerCase() ] = value;
382 getAllResponseHeaders: function() {
383 return state === 2 ? responseHeadersString : null;
386 // Builds headers hashtable if needed
387 getResponseHeader: function( key ) {
390 if ( !responseHeaders ) {
391 responseHeaders = {};
392 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
393 responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
396 match = responseHeaders[ key.toLowerCase() ];
398 return match || null;
401 // Cancel the request
402 abort: function( statusText ) {
404 transport.abort( statusText || "abort" );
406 done( 0, statusText );
411 // Callback for when everything is done
412 // It is defined here because jslint complains if it is declared
413 // at the end of the function (which would be more logical and readable)
414 function done( status, statusText, responses, headers) {
421 // State is "done" now
424 // Clear timeout if it exists
425 if ( timeoutTimer ) {
426 clearTimeout( timeoutTimer );
429 // Dereference transport for early garbage collection
430 // (no matter how long the jXHR object will be used)
431 transport = undefined;
433 // Cache response headers
434 responseHeadersString = headers || "";
437 jXHR.readyState = status ? 4 : 0;
441 error = ( statusText = statusText || "error" ),
442 response = responses ? ajaxHandleResponses( s, jXHR, responses ) : undefined,
446 // If successful, handle type chaining
447 if ( status >= 200 && status < 300 || status === 304 ) {
449 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
450 if ( s.ifModified ) {
452 if ( ( lastModified = jXHR.getResponseHeader( "Last-Modified" ) ) ) {
453 jQuery.lastModified[ s.url ] = lastModified;
455 if ( ( etag = jXHR.getResponseHeader( "Etag" ) ) ) {
456 jQuery.etag[ s.url ] = etag;
461 if ( status === 304 ) {
463 statusText = "notmodified";
470 success = ajaxConvert( s, response );
471 statusText = "success";
474 // We have a parsererror
475 statusText = "parsererror";
481 // Set data for the fake xhr object
482 jXHR.status = status;
483 jXHR.statusText = statusText;
487 deferred.resolveWith( callbackContext, [ success, statusText, jXHR ] );
489 deferred.rejectWith( callbackContext, [ jXHR, statusText, error ] );
492 // Status-dependent callbacks
493 jXHR.statusCode( statusCode );
494 statusCode = undefined;
497 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
498 [ jXHR, s, isSuccess ? success : error ] );
502 completeDeferred.resolveWith( callbackContext, [ jXHR, statusText ] );
505 globalEventContext.trigger( "ajaxComplete", [ jXHR, s] );
506 // Handle the global AJAX counter
507 if ( !( --jQuery.active ) ) {
508 jQuery.event.trigger( "ajaxStop" );
514 deferred.promise( jXHR );
515 jXHR.success = jXHR.done;
516 jXHR.error = jXHR.fail;
517 jXHR.complete = completeDeferred.done;
519 // Status-dependent callbacks
520 jXHR.statusCode = function( map ) {
525 statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
528 tmp = map[ jXHR.status ];
529 jXHR.then( tmp, tmp );
535 // Remove hash character (#7531: and string promotion)
536 // We also use the url parameter if available
537 s.url = ( "" + ( url || s.url ) ).replace( rhash, "" );
539 // Extract dataTypes list
540 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
542 // Determine if a cross-domain request is in order
543 if ( !s.crossDomain ) {
544 parts = rurl.exec( s.url.toLowerCase() );
547 ( parts[ 1 ] && parts[ 1 ] != protocol ||
548 parts[ 2 ] != loc.hostname ||
549 ( parts[ 3 ] || ( ( parts[ 1 ] || protocol ) === "http:" ? 80 : 443 ) ) !=
550 ( loc.port || ( protocol === "http:" ? 80 : 443 ) ) )
554 // Convert data if not already a string
555 if ( s.data && s.processData && typeof s.data !== "string" ) {
556 s.data = jQuery.param( s.data, s.traditional );
560 inspectPrefiltersOrTransports( prefilters, s, options );
562 // Uppercase the type
563 s.type = s.type.toUpperCase();
565 // Determine if request has content
566 s.hasContent = !rnoContent.test( s.type );
568 // Watch for a new set of requests
569 if ( s.global && jQuery.active++ === 0 ) {
570 jQuery.event.trigger( "ajaxStart" );
573 // More options handling for requests with no content
574 if ( !s.hasContent ) {
576 // If data is available, append data to url
578 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
581 // Add anti-cache in url if needed
582 if ( s.cache === false ) {
584 var ts = jQuery.now(),
585 // try replacing _= if it is there
586 ret = s.url.replace( rts, "$1_=" + ts );
588 // if nothing was replaced, add timestamp to the end
589 s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
593 // Set the correct header, if data is being sent
594 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
595 requestHeaders[ "content-type" ] = s.contentType;
598 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
599 if ( s.ifModified ) {
600 if ( jQuery.lastModified[ s.url ] ) {
601 requestHeaders[ "if-modified-since" ] = jQuery.lastModified[ s.url ];
603 if ( jQuery.etag[ s.url ] ) {
604 requestHeaders[ "if-none-match" ] = jQuery.etag[ s.url ];
608 // Set the Accepts header for the server, depending on the dataType
609 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
610 s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
613 // Check for headers option
614 for ( i in s.headers ) {
615 requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
618 // Allow custom headers/mimetypes and early abort
619 if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jXHR, s ) === false || state === 2 ) ) {
620 // Abort if not done already
627 // Install callbacks on deferreds
628 for ( i in { success: 1, error: 1, complete: 1 } ) {
633 transport = inspectPrefiltersOrTransports( transports, s, options );
635 // If no transport, we auto-abort
637 done( 0, "notransport" );
639 // Set state as sending
640 state = jXHR.readyState = 1;
643 globalEventContext.trigger( "ajaxSend", [ jXHR, s ] );
646 if ( s.async && s.timeout > 0 ) {
647 timeoutTimer = setTimeout( function(){
648 jXHR.abort( "timeout" );
653 transport.send( requestHeaders, done );
655 // Propagate exception as error if not done
656 if ( status === 1 ) {
657 done( 0, "error", "" + e );
659 // Simply rethrow otherwise
669 // Serialize an array of form elements or a set of
670 // key/values into a query string
671 param: function( a, traditional ) {
673 add = function( key, value ) {
674 // If value is a function, invoke it and return its value
675 value = jQuery.isFunction( value ) ? value() : value;
676 s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
679 // Set traditional to true for jQuery <= 1.3.2 behavior.
680 if ( traditional === undefined ) {
681 traditional = jQuery.ajaxSettings.traditional;
684 // If an array was passed in, assume that it is an array of form elements.
685 if ( jQuery.isArray( a ) || a.jquery ) {
686 // Serialize the form elements
687 jQuery.each( a, function() {
688 add( this.name, this.value );
692 // If traditional, encode the "old" way (the way 1.3.2 or older
693 // did it), otherwise encode params recursively.
694 for ( var prefix in a ) {
695 buildParams( prefix, a[ prefix ], traditional, add );
699 // Return the resulting serialization
700 return s.join( "&" ).replace( r20, "+" );
704 function buildParams( prefix, obj, traditional, add ) {
705 if ( jQuery.isArray( obj ) && obj.length ) {
706 // Serialize array item.
707 jQuery.each( obj, function( i, v ) {
708 if ( traditional || rbracket.test( prefix ) ) {
709 // Treat each array item as a scalar.
713 // If array item is non-scalar (array or object), encode its
714 // numeric index to resolve deserialization ambiguity issues.
715 // Note that rack (as of 1.0.0) can't currently deserialize
716 // nested arrays properly, and attempting to do so may cause
717 // a server error. Possible fixes are to modify rack's
718 // deserialization algorithm or to provide an option or flag
719 // to force array serialization to be shallow.
720 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
724 } else if ( !traditional && obj != null && typeof obj === "object" ) {
725 // If we see an array here, it is empty and should be treated as an empty
727 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
730 // Serialize object item.
732 jQuery.each( obj, function( k, v ) {
733 buildParams( prefix + "[" + k + "]", v, traditional, add );
738 // Serialize scalar item.
743 // This is still on the jQuery object... for now
744 // Want to move this to jQuery.ajax some day
747 // Counter for holding the number of active queries
750 // Last-Modified header cache for next request
756 /* Handles responses to an ajax request:
757 * - sets all responseXXX fields accordingly
758 * - finds the right dataType (mediates between content-type and expected dataType)
759 * - returns the corresponding response
761 function ajaxHandleResponses( s, jXHR, responses ) {
763 var contents = s.contents,
764 dataTypes = s.dataTypes,
765 responseFields = s.responseFields,
771 // Fill responseXXX fields
772 for( type in responseFields ) {
773 if ( type in responses ) {
774 jXHR[ responseFields[type] ] = responses[ type ];
778 // Remove auto dataType and get content-type in the process
779 while( dataTypes[ 0 ] === "*" ) {
781 if ( ct === undefined ) {
782 ct = jXHR.getResponseHeader( "content-type" );
786 // Check if we're dealing with a known content-type
788 for ( type in contents ) {
789 if ( contents[ type ] && contents[ type ].test( ct ) ) {
790 dataTypes.unshift( type );
796 // Check to see if we have a response for the expected dataType
797 if ( dataTypes[ 0 ] in responses ) {
798 finalDataType = dataTypes[ 0 ];
800 // Try convertible dataTypes
801 for ( type in responses ) {
802 if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
803 finalDataType = type;
806 if ( !firstDataType ) {
807 firstDataType = type;
810 // Or just use first one
811 finalDataType = finalDataType || firstDataType;
814 // If we found a dataType
815 // We add the dataType to the list if needed
816 // and return the corresponding response
817 if ( finalDataType ) {
818 if ( finalDataType !== dataTypes[ 0 ] ) {
819 dataTypes.unshift( finalDataType );
821 return responses[ finalDataType ];
825 // Chain conversions given the request and the original response
826 function ajaxConvert( s, response ) {
828 // Apply the dataFilter if provided
829 if ( s.dataFilter ) {
830 response = s.dataFilter( response, s.dataType );
833 var dataTypes = s.dataTypes,
834 converters = s.converters,
836 length = dataTypes.length,
838 // Current and previous dataTypes
839 current = dataTypes[ 0 ],
841 // Conversion expression
843 // Conversion function
845 // Conversion functions (when text is used in-between)
849 // For each dataType in the chain
850 for( i = 1; i < length; i++ ) {
854 current = dataTypes[ i ];
856 // If current is auto dataType, update it to prev
857 if( current === "*" ) {
859 // If no auto and dataTypes are actually different
860 } else if ( prev !== "*" && prev !== current ) {
863 conversion = prev + " " + current;
864 conv = converters[ conversion ] || converters[ "* " + current ];
866 // If there is no direct converter, search transitively
869 for( conv1 in converters ) {
870 tmp = conv1.split( " " );
871 if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
872 conv2 = converters[ tmp[1] + " " + current ];
874 conv1 = converters[ conv1 ];
875 if ( conv1 === true ) {
877 } else if ( conv2 === true ) {
885 // If we found no converter, dispatch an error
886 if ( !( conv || conv2 ) ) {
887 jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
889 // If found converter is not an equivalence
890 if ( conv !== true ) {
891 // Convert with 1 or 2 converters accordingly
892 response = conv ? conv( response ) : conv2( conv1(response) );