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 */, tested /* internal */ ) {
81 dataType = dataType || options.dataTypes[ 0 ];
82 tested = tested || {};
84 tested[ dataType ] = true;
86 var list = structure[ dataType ],
88 length = list ? list.length : 0,
89 executeOnly = structure === prefilters,
92 for(; i < length && !( executeOnly ? typeof selected === "string" && !tested[ selected ] : selected ); i++ ) {
93 selected = list[ i ]( options, originalOptions );
95 // If we got redirected to another dataType
97 if ( typeof selected === "string" && !tested[ selected ] ) {
98 options.dataTypes.unshift( selected );
99 selected = inspectPrefiltersOrTransports(
100 structure, options, originalOptions, selected, tested );
102 // If we're only executing or nothing was selected
103 // we try the catchall dataType if not done already
104 } else if ( ( executeOnly || !selected ) && !tested[ "*" ] ) {
105 selected = inspectPrefiltersOrTransports(
106 structure, options, originalOptions, "*" ,tested );
108 // unnecessary when only executing (prefilters)
109 // but it'll be ignored by the caller in that case
114 load: function( url, params, callback ) {
115 if ( typeof url !== "string" && _load ) {
116 return _load.apply( this, arguments );
118 // Don't do a request if no elements are being requested
119 } else if ( !this.length ) {
123 var off = url.indexOf( " " );
125 var selector = url.slice( off, url.length );
126 url = url.slice( 0, off );
129 // Default to a GET request
132 // If the second parameter was provided
134 // If it's a function
135 if ( jQuery.isFunction( params ) ) {
136 // We assume that it's the callback
140 // Otherwise, build a param string
141 } else if ( typeof params === "object" ) {
142 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
149 // Request the remote document
155 // Complete callback (responseText is used internally)
156 complete: function( jXHR, status, responseText ) {
157 // Store the response as specified by the jXHR object
158 responseText = jXHR.responseText;
159 // If successful, inject the HTML into all the matched elements
160 if ( jXHR.isResolved() ) {
161 // #4825: Get the actual response in case
162 // a dataFilter is present in ajaxSettings
163 jXHR.done(function( r ) {
166 // See if a selector was specified
167 self.html( selector ?
168 // Create a dummy div to hold the results
170 // inject the contents of the document in, removing the scripts
171 // to avoid any 'Permission Denied' errors in IE
172 .append(responseText.replace(rscript, ""))
174 // Locate the specified elements
177 // If not, just inject the full result
182 self.each( callback, [ responseText, status, jXHR ] );
190 serialize: function() {
191 return jQuery.param( this.serializeArray() );
194 serializeArray: function() {
195 return this.map(function(){
196 return this.elements ? jQuery.makeArray( this.elements ) : this;
199 return this.name && !this.disabled &&
200 ( this.checked || rselectTextarea.test( this.nodeName ) ||
201 rinput.test( this.type ) );
203 .map(function( i, elem ){
204 var val = jQuery( this ).val();
208 jQuery.isArray( val ) ?
209 jQuery.map( val, function( val, i ){
210 return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
212 { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
217 // Attach a bunch of functions for handling common AJAX events
218 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
219 jQuery.fn[ o ] = function( f ){
220 return this.bind( o, f );
224 jQuery.each( [ "get", "post" ], function( i, method ) {
225 jQuery[ method ] = function( url, data, callback, type ) {
226 // shift arguments if data argument was omitted
227 if ( jQuery.isFunction( data ) ) {
228 type = type || callback;
245 getScript: function( url, callback ) {
246 return jQuery.get( url, null, callback, "script" );
249 getJSON: function( url, data, callback ) {
250 return jQuery.get( url, data, callback, "json" );
253 ajaxSetup: function( settings ) {
254 jQuery.extend( true, jQuery.ajaxSettings, settings );
255 if ( settings.context ) {
256 jQuery.ajaxSettings.context = settings.context;
264 contentType: "application/x-www-form-urlencoded",
280 xml: "application/xml, text/xml",
283 json: "application/json, text/javascript",
298 // List of data converters
299 // 1) key format is "source_type destination_type" (a single space in-between)
300 // 2) the catchall symbol "*" can be used for source_type
303 // Convert anything to text
304 "* text": window.String,
306 // Text to html (true = no transformation)
309 // Evaluate text as a json expression
310 "text json": jQuery.parseJSON,
313 "text xml": jQuery.parseXML
317 ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
318 ajaxTransport: addToPrefiltersOrTransports( transports ),
321 ajax: function( url, options ) {
323 // If options is not an object,
324 // we simulate pre-1.5 signature
325 if ( typeof options !== "object" ) {
330 // Force options to be an object
331 options = options || {};
333 var // Create the final options object
334 s = jQuery.extend( true, {}, jQuery.ajaxSettings, options ),
335 // Callbacks contexts
336 // We force the original context if it exists
337 // or take it from jQuery.ajaxSettings otherwise
338 // (plain objects used as context get extended)
340 ( s.context = ( "context" in options ? options : jQuery.ajaxSettings ).context ) || s,
341 globalEventContext = callbackContext === s ? jQuery.event : jQuery( callbackContext ),
343 deferred = jQuery.Deferred(),
344 completeDeferred = jQuery._Deferred(),
345 // Status-dependent callbacks
346 statusCode = s.statusCode || {},
347 // Headers (they are sent all at once)
350 responseHeadersString,
356 // Cross-domain detection vars
357 loc = document.location,
358 protocol = loc.protocol || "http:",
370 setRequestHeader: function( name, value ) {
372 requestHeaders[ name.toLowerCase() ] = value;
378 getAllResponseHeaders: function() {
379 return state === 2 ? responseHeadersString : null;
382 // Builds headers hashtable if needed
383 getResponseHeader: function( key ) {
386 if ( !responseHeaders ) {
387 responseHeaders = {};
388 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
389 responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
392 match = responseHeaders[ key.toLowerCase() ];
394 return match || null;
397 // Cancel the request
398 abort: function( statusText ) {
400 transport.abort( statusText || "abort" );
402 done( 0, statusText );
407 // Callback for when everything is done
408 // It is defined here because jslint complains if it is declared
409 // at the end of the function (which would be more logical and readable)
410 function done( status, statusText, responses, headers) {
417 // State is "done" now
420 // Clear timeout if it exists
421 if ( timeoutTimer ) {
422 clearTimeout( timeoutTimer );
425 // Dereference transport for early garbage collection
426 // (no matter how long the jXHR object will be used)
427 transport = undefined;
429 // Cache response headers
430 responseHeadersString = headers || "";
433 jXHR.readyState = status ? 4 : 0;
437 error = ( statusText = statusText || "error" ),
438 response = responses ? ajaxHandleResponses( s, jXHR, responses ) : undefined,
442 // If successful, handle type chaining
443 if ( status >= 200 && status < 300 || status === 304 ) {
445 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
446 if ( s.ifModified ) {
448 if ( ( lastModified = jXHR.getResponseHeader( "Last-Modified" ) ) ) {
449 jQuery.lastModified[ s.url ] = lastModified;
451 if ( ( etag = jXHR.getResponseHeader( "Etag" ) ) ) {
452 jQuery.etag[ s.url ] = etag;
457 if ( status === 304 ) {
459 statusText = "notmodified";
466 success = ajaxConvert( s, response );
467 statusText = "success";
470 // We have a parsererror
471 statusText = "parsererror";
477 // Set data for the fake xhr object
478 jXHR.status = status;
479 jXHR.statusText = statusText;
483 deferred.resolveWith( callbackContext, [ success, statusText, jXHR ] );
485 deferred.rejectWith( callbackContext, [ jXHR, statusText, error ] );
488 // Status-dependent callbacks
489 jXHR.statusCode( statusCode );
490 statusCode = undefined;
493 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
494 [ jXHR, s, isSuccess ? success : error ] );
498 completeDeferred.resolveWith( callbackContext, [ jXHR, statusText ] );
501 globalEventContext.trigger( "ajaxComplete", [ jXHR, s] );
502 // Handle the global AJAX counter
503 if ( !( --jQuery.active ) ) {
504 jQuery.event.trigger( "ajaxStop" );
510 deferred.promise( jXHR );
511 jXHR.success = jXHR.done;
512 jXHR.error = jXHR.fail;
513 jXHR.complete = completeDeferred.done;
515 // Status-dependent callbacks
516 jXHR.statusCode = function( map ) {
521 statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
524 tmp = map[ jXHR.status ];
525 jXHR.then( tmp, tmp );
531 // Remove hash character (#7531: and string promotion)
532 // We also use the url parameter if available
533 s.url = ( "" + ( url || s.url ) ).replace( rhash, "" );
535 // Extract dataTypes list
536 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
538 // Determine if a cross-domain request is in order
539 if ( !s.crossDomain ) {
540 parts = rurl.exec( s.url.toLowerCase() );
543 ( parts[ 1 ] && parts[ 1 ] != protocol ||
544 parts[ 2 ] != loc.hostname ||
545 ( parts[ 3 ] || ( ( parts[ 1 ] || protocol ) === "http:" ? 80 : 443 ) ) !=
546 ( loc.port || ( protocol === "http:" ? 80 : 443 ) ) )
550 // Convert data if not already a string
551 if ( s.data && s.processData && typeof s.data !== "string" ) {
552 s.data = jQuery.param( s.data, s.traditional );
556 inspectPrefiltersOrTransports( prefilters, s, options );
558 // Uppercase the type
559 s.type = s.type.toUpperCase();
561 // Determine if request has content
562 s.hasContent = !rnoContent.test( s.type );
564 // Watch for a new set of requests
565 if ( s.global && jQuery.active++ === 0 ) {
566 jQuery.event.trigger( "ajaxStart" );
569 // More options handling for requests with no content
570 if ( !s.hasContent ) {
572 // If data is available, append data to url
574 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
577 // Add anti-cache in url if needed
578 if ( s.cache === false ) {
580 var ts = jQuery.now(),
581 // try replacing _= if it is there
582 ret = s.url.replace( rts, "$1_=" + ts );
584 // if nothing was replaced, add timestamp to the end
585 s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
589 // Set the correct header, if data is being sent
590 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
591 requestHeaders[ "content-type" ] = s.contentType;
594 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
595 if ( s.ifModified ) {
596 if ( jQuery.lastModified[ s.url ] ) {
597 requestHeaders[ "if-modified-since" ] = jQuery.lastModified[ s.url ];
599 if ( jQuery.etag[ s.url ] ) {
600 requestHeaders[ "if-none-match" ] = jQuery.etag[ s.url ];
604 // Set the Accepts header for the server, depending on the dataType
605 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
606 s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
609 // Check for headers option
610 for ( i in s.headers ) {
611 requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
614 // Allow custom headers/mimetypes and early abort
615 if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jXHR, s ) === false || state === 2 ) ) {
616 // Abort if not done already
623 // Install callbacks on deferreds
624 for ( i in { success: 1, error: 1, complete: 1 } ) {
629 transport = inspectPrefiltersOrTransports( transports, s, options );
631 // If no transport, we auto-abort
633 done( 0, "notransport" );
635 // Set state as sending
636 state = jXHR.readyState = 1;
639 globalEventContext.trigger( "ajaxSend", [ jXHR, s ] );
642 if ( s.async && s.timeout > 0 ) {
643 timeoutTimer = setTimeout( function(){
644 jXHR.abort( "timeout" );
649 transport.send( requestHeaders, done );
651 // Propagate exception as error if not done
652 if ( status === 1 ) {
653 done( 0, "error", "" + e );
655 // Simply rethrow otherwise
665 // Serialize an array of form elements or a set of
666 // key/values into a query string
667 param: function( a, traditional ) {
669 add = function( key, value ) {
670 // If value is a function, invoke it and return its value
671 value = jQuery.isFunction( value ) ? value() : value;
672 s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
675 // Set traditional to true for jQuery <= 1.3.2 behavior.
676 if ( traditional === undefined ) {
677 traditional = jQuery.ajaxSettings.traditional;
680 // If an array was passed in, assume that it is an array of form elements.
681 if ( jQuery.isArray( a ) || a.jquery ) {
682 // Serialize the form elements
683 jQuery.each( a, function() {
684 add( this.name, this.value );
688 // If traditional, encode the "old" way (the way 1.3.2 or older
689 // did it), otherwise encode params recursively.
690 for ( var prefix in a ) {
691 buildParams( prefix, a[ prefix ], traditional, add );
695 // Return the resulting serialization
696 return s.join( "&" ).replace( r20, "+" );
700 function buildParams( prefix, obj, traditional, add ) {
701 if ( jQuery.isArray( obj ) && obj.length ) {
702 // Serialize array item.
703 jQuery.each( obj, function( i, v ) {
704 if ( traditional || rbracket.test( prefix ) ) {
705 // Treat each array item as a scalar.
709 // If array item is non-scalar (array or object), encode its
710 // numeric index to resolve deserialization ambiguity issues.
711 // Note that rack (as of 1.0.0) can't currently deserialize
712 // nested arrays properly, and attempting to do so may cause
713 // a server error. Possible fixes are to modify rack's
714 // deserialization algorithm or to provide an option or flag
715 // to force array serialization to be shallow.
716 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
720 } else if ( !traditional && obj != null && typeof obj === "object" ) {
721 // If we see an array here, it is empty and should be treated as an empty
723 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
726 // Serialize object item.
728 jQuery.each( obj, function( k, v ) {
729 buildParams( prefix + "[" + k + "]", v, traditional, add );
734 // Serialize scalar item.
739 // This is still on the jQuery object... for now
740 // Want to move this to jQuery.ajax some day
743 // Counter for holding the number of active queries
746 // Last-Modified header cache for next request
752 /* Handles responses to an ajax request:
753 * - sets all responseXXX fields accordingly
754 * - finds the right dataType (mediates between content-type and expected dataType)
755 * - returns the corresponding response
757 function ajaxHandleResponses( s, jXHR, responses ) {
759 var contents = s.contents,
760 dataTypes = s.dataTypes,
761 responseFields = s.responseFields,
767 // Fill responseXXX fields
768 for( type in responseFields ) {
769 if ( type in responses ) {
770 jXHR[ responseFields[type] ] = responses[ type ];
774 // Remove auto dataType and get content-type in the process
775 while( dataTypes[ 0 ] === "*" ) {
777 if ( ct === undefined ) {
778 ct = jXHR.getResponseHeader( "content-type" );
782 // Check if we're dealing with a known content-type
784 for ( type in contents ) {
785 if ( contents[ type ] && contents[ type ].test( ct ) ) {
786 dataTypes.unshift( type );
792 // Check to see if we have a response for the expected dataType
793 if ( dataTypes[ 0 ] in responses ) {
794 finalDataType = dataTypes[ 0 ];
796 // Try convertible dataTypes
797 for ( type in responses ) {
798 if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
799 finalDataType = type;
802 if ( !firstDataType ) {
803 firstDataType = type;
806 // Or just use first one
807 finalDataType = finalDataType || firstDataType;
810 // If we found a dataType
811 // We add the dataType to the list if needed
812 // and return the corresponding response
813 if ( finalDataType ) {
814 if ( finalDataType !== dataTypes[ 0 ] ) {
815 dataTypes.unshift( finalDataType );
817 return responses[ finalDataType ];
821 // Chain conversions given the request and the original response
822 function ajaxConvert( s, response ) {
824 // Apply the dataFilter if provided
825 if ( s.dataFilter ) {
826 response = s.dataFilter( response, s.dataType );
829 var dataTypes = s.dataTypes,
830 converters = s.converters,
832 length = dataTypes.length,
834 // Current and previous dataTypes
835 current = dataTypes[ 0 ],
837 // Conversion expression
839 // Conversion function
841 // Conversion functions (when text is used in-between)
845 // For each dataType in the chain
846 for( i = 1; i < length; i++ ) {
850 current = dataTypes[ i ];
852 // If current is auto dataType, update it to prev
853 if( current === "*" ) {
855 // If no auto and dataTypes are actually different
856 } else if ( prev !== "*" && prev !== current ) {
859 conversion = prev + " " + current;
860 conv = converters[ conversion ] || converters[ "* " + current ];
862 // If there is no direct converter, search transitively
865 for( conv1 in converters ) {
866 tmp = conv1.split( " " );
867 if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
868 conv2 = converters[ tmp[1] + " " + current ];
870 conv1 = converters[ conv1 ];
871 if ( conv1 === true ) {
873 } else if ( conv2 === true ) {
881 // If we found no converter, dispatch an error
882 if ( !( conv || conv2 ) ) {
883 jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
885 // If found converter is not an equivalence
886 if ( conv !== true ) {
887 // Convert with 1 or 2 converters accordingly
888 response = conv ? conv( response ) : conv2( conv1(response) );