6 rheaders = /^(.*?):\s*(.*?)\r?$/mg, // IE leaves an \r character at EOL
7 rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
8 rnoContent = /^(?:GET|HEAD)$/,
10 rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
11 rselectTextarea = /^(?:select|textarea)/i,
12 rts = /([?&])_=[^&]*/,
13 rurl = /^(\w+:)?\/\/([^\/?#:]+)(?::(\d+))?/,
17 sliceFunc = Array.prototype.slice,
19 // Keep a copy of the old load method
20 _load = jQuery.fn.load;
23 load: function( url, params, callback ) {
24 if ( typeof url !== "string" && _load ) {
25 return _load.apply( this, arguments );
27 // Don't do a request if no elements are being requested
28 } else if ( !this.length ) {
32 var off = url.indexOf(" ");
34 var selector = url.slice(off, url.length);
35 url = url.slice(0, off);
38 // Default to a GET request
41 // If the second parameter was provided
44 if ( jQuery.isFunction( params ) ) {
45 // We assume that it's the callback
49 // Otherwise, build a param string
50 } else if ( typeof params === "object" ) {
51 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
58 // Request the remote document
64 // Complete callback (responseText is used internally)
65 complete: function( jXHR, status, responseText ) {
66 // Store the response as specified by the jXHR object
67 responseText = jXHR.responseText;
68 // If successful, inject the HTML into all the matched elements
69 if ( jXHR.isResolved() ) {
70 // #4825: Get the actual response in case
71 // a dataFilter is present in ajaxSettings
72 jXHR.done(function( r ) {
75 // See if a selector was specified
77 // Create a dummy div to hold the results
79 // inject the contents of the document in, removing the scripts
80 // to avoid any 'Permission Denied' errors in IE
81 .append(responseText.replace(rscript, ""))
83 // Locate the specified elements
86 // If not, just inject the full result
91 self.each( callback, [responseText, status, jXHR] );
99 serialize: function() {
100 return jQuery.param(this.serializeArray());
103 serializeArray: function() {
104 return this.map(function(){
105 return this.elements ? jQuery.makeArray(this.elements) : this;
108 return this.name && !this.disabled &&
109 (this.checked || rselectTextarea.test(this.nodeName) ||
110 rinput.test(this.type));
112 .map(function(i, elem){
113 var val = jQuery(this).val();
117 jQuery.isArray(val) ?
118 jQuery.map( val, function(val, i){
119 return { name: elem.name, value: val.replace(rCRLF, "\r\n") };
121 { name: elem.name, value: val.replace(rCRLF, "\r\n") };
126 // Attach a bunch of functions for handling common AJAX events
127 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function(i,o){
128 jQuery.fn[o] = function(f){
129 return this.bind(o, f);
133 jQuery.each( [ "get", "post" ], function( i, method ) {
134 jQuery[ method ] = function( url, data, callback, type ) {
135 // shift arguments if data argument was omited
136 if ( jQuery.isFunction( data ) ) {
137 type = type || callback;
154 getScript: function( url, callback ) {
155 return jQuery.get(url, null, callback, "script");
158 getJSON: function( url, data, callback ) {
159 return jQuery.get(url, data, callback, "json");
162 ajaxSetup: function( settings ) {
163 jQuery.extend( true, jQuery.ajaxSettings, settings );
164 if ( settings.context ) {
165 jQuery.ajaxSettings.context = settings.context;
173 contentType: "application/x-www-form-urlencoded",
189 xml: "application/xml, text/xml",
192 json: "application/json, text/javascript",
203 // 1) They are useful to introduce custom dataTypes (see transport/jsonp for an example)
204 // 2) These are called:
205 // * BEFORE asking for a transport
206 // * AFTER param serialization (s.data is a string if s.processData is true)
207 // 3) key is the dataType
208 // 4) the catchall symbol "*" can be used
209 // 5) execution will start with transport dataType and THEN continue down to "*" if needed
212 // Transports bindings
213 // 1) key is the dataType
214 // 2) the catchall symbol "*" can be used
215 // 3) selection will start with transport dataType and THEN go to "*" if needed
218 // List of data converters
219 // 1) key format is "source_type destination_type" (a single space in-between)
220 // 2) the catchall symbol "*" can be used for source_type
223 // Convert anything to text
224 "* text": window.String,
226 // Text to html (true = no transformation)
229 // Evaluate text as a json expression
230 "text json": jQuery.parseJSON,
233 "text xml": jQuery.parseXML
236 // Utility function that handles dataType when response is received
237 // (for those transports that can give text or xml responses)
238 determineDataType: function( ct , text , xml ) {
241 contents = s.contents,
244 dataTypes = s.dataTypes,
245 transportDataType = dataTypes[0],
248 // Auto (xml, json, script or text determined given headers)
249 if ( transportDataType === "*" ) {
251 for ( type in contents ) {
252 if ( ( regexp = contents[ type ] ) && regexp.test( ct ) ) {
253 transportDataType = dataTypes[0] = type;
259 // xml and parsed as such
260 if ( transportDataType === "xml" &&
262 xml.documentElement /* #4958 */ ) {
266 // Text response was provided
271 // If it's not really text, defer to converters
272 if ( transportDataType !== "text" ) {
273 dataTypes.unshift( "text" );
283 ajaxPrefilter: function( a , b ) {
284 ajaxPrefilterOrTransport( "prefilters" , a , b );
287 ajaxTransport: function( a , b ) {
288 return ajaxPrefilterOrTransport( "transports" , a , b );
292 ajax: function( url , options ) {
294 // If options is not an object,
295 // we simulate pre-1.5 signature
296 if ( typeof( options ) !== "object" ) {
301 // Force options to be an object
302 options = options || {};
304 var // Create the final options object
305 s = jQuery.extend( true , {} , jQuery.ajaxSettings , options ),
307 jQuery_lastModified = jQuery.lastModified,
308 jQuery_etag = jQuery.etag,
309 // Callbacks contexts
310 // We force the original context if it exists
311 // or take it from jQuery.ajaxSettings otherwise
312 // (plain objects used as context get extended)
314 ( s.context = ( "context" in options ? options : jQuery.ajaxSettings ).context ) || s,
315 globalEventContext = callbackContext === s ? jQuery.event : jQuery( callbackContext ),
317 deferred = jQuery.Deferred(),
318 completeDeferred = jQuery._Deferred(),
319 // Status-dependent callbacks
320 statusCode = s.statusCode || {},
321 // Headers (they are sent all at once)
324 responseHeadersString,
330 // Cross-domain detection vars
331 loc = document.location,
332 protocol = loc.protocol || "http:",
344 setRequestHeader: function(name,value) {
346 requestHeaders[ name.toLowerCase() ] = value;
352 getAllResponseHeaders: function() {
353 return state === 2 ? responseHeadersString : null;
356 // Builds headers hashtable if needed
357 getResponseHeader: function( key ) {
363 if ( !responseHeaders ) {
365 responseHeaders = {};
367 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
368 responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
371 match = responseHeaders[ key.toLowerCase() ];
375 return match || null;
378 // Cancel the request
379 abort: function( statusText ) {
381 transport.abort( statusText || "abort" );
383 done( 0 , statusText );
388 // Callback for when everything is done
389 // It is defined here because jslint complains if it is declared
390 // at the end of the function (which would be more logical and readable)
391 function done( status , statusText , response , headers) {
398 // State is "done" now
401 // Dereference transport for early garbage collection
402 // (no matter how long the jXHR transport will be used
403 transport = undefined;
406 jXHR.readyState = status ? 4 : 0;
408 // Cache response headers
409 responseHeadersString = headers || "";
411 // Clear timeout if it exists
412 if ( timeoutTimer ) {
413 clearTimeout(timeoutTimer);
418 // and ifModified status
419 ifModified = s.ifModified,
428 // To keep track of statusCode based callbacks
431 // If successful, handle type chaining
432 if ( status >= 200 && status < 300 || status === 304 ) {
434 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
435 if ( s.ifModified ) {
437 var lastModified = jXHR.getResponseHeader("Last-Modified"),
438 etag = jXHR.getResponseHeader("Etag");
441 jQuery_lastModified[ s.url ] = lastModified;
444 jQuery_etag[ s.url ] = etag;
449 if ( status === 304 ) {
451 // Set the statusText accordingly
452 statusText = "notmodified";
459 // Set the statusText accordingly
460 statusText = "success";
462 // Chain data conversions and determine the final value
463 // (if an exception is thrown in the process, it'll be notified as an error)
471 // Conversion expression
473 // Conversion function
475 // Conversion functions (when text is used in-between)
478 // Local references to dataTypes & converters
479 dataTypes = s.dataTypes,
480 converters = s.converters,
481 // DataType to responseXXX field mapping
487 // For each dataType in the chain
488 for( i = 0 ; i < dataTypes.length ; i++ ) {
490 current = dataTypes[ i ];
492 // If a responseXXX field for this dataType exists
493 // and if it hasn't been set yet
494 if ( responses[ current ] ) {
496 jXHR[ "response" + responses[ current ] ] = response;
498 responses[ current ] = 0;
501 // If this is not the first element
504 // Get the dataType to convert from
505 prev = dataTypes[ i - 1 ];
507 // If no catch-all and dataTypes are actually different
508 if ( prev !== "*" && current !== "*" && prev !== current ) {
511 conversion = prev + " " + current;
512 conv = converters[ conversion ] || converters[ "* " + current ];
516 // If there is no direct converter and none of the dataTypes is text
517 if ( ! conv && prev !== "text" && current !== "text" ) {
518 // Try with text in-between
519 conv1 = converters[ prev + " text" ] || converters[ "* text" ];
520 conv2 = converters[ "text " + current ];
521 // Revert back to a single converter
522 // if one of the converter is an equivalence
523 if ( conv1 === true ) {
525 } else if ( conv2 === true ) {
529 // If we found no converter, dispatch an error
530 if ( ! ( conv || conv1 && conv2 ) ) {
533 // If found converter is not an equivalence
534 if ( conv !== true ) {
535 // Convert with 1 or 2 converters accordingly
536 response = conv ? conv( response ) : conv2( conv1( response ) );
539 // If it is the first element of the chain
540 // and we have a dataFilter
541 } else if ( s.dataFilter ) {
542 // Apply the dataFilter
543 response = s.dataFilter( response , current );
544 // Get dataTypes again in case the filter changed them
545 dataTypes = s.dataTypes;
550 // We have a real success
554 // If an exception was thrown
557 // We have a parsererror
558 statusText = "parsererror";
564 // if not success, mark it as an error
567 error = statusText = statusText || "error";
569 // Set responseText if needed
571 jXHR.responseText = response;
575 // Set data for the fake xhr object
576 jXHR.status = status;
577 jXHR.statusText = statusText;
581 deferred.fire( callbackContext , [ success , statusText , jXHR ] );
583 deferred.fireReject( callbackContext , [ jXHR , statusText , error ] );
586 // Status-dependent callbacks
587 oldStatusCode = statusCode;
588 statusCode = undefined;
589 jXHR.statusCode( oldStatusCode );
592 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ) ,
593 [ jXHR , s , isSuccess ? success : error ] );
597 completeDeferred.fire( callbackContext, [ jXHR , statusText ] );
600 globalEventContext.trigger( "ajaxComplete" , [ jXHR , s] );
601 // Handle the global AJAX counter
602 if ( ! --jQuery.active ) {
603 jQuery.event.trigger( "ajaxStop" );
609 deferred.promise( jXHR );
610 jXHR.success = jXHR.done;
611 jXHR.error = jXHR.fail;
612 jXHR.complete = completeDeferred.done;
614 // Status-dependent callbacks
615 jXHR.statusCode = function( map ) {
620 statusCode[ tmp ] = [ statusCode[ tmp ] , map[ tmp ] ];
623 tmp = map[ jXHR.status ];
624 jXHR.done( tmp ).fail( tmp );
630 // Remove hash character (#7531: and string promotion)
631 // We also use the url parameter if available
632 s.url = ( "" + ( url || s.url ) ).replace( rhash , "" );
634 // Extract dataTypes list
635 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( /\s+/ );
637 // Determine if a cross-domain request is in order
638 if ( ! s.crossDomain ) {
639 parts = rurl.exec( s.url.toLowerCase() );
642 ( parts[ 1 ] && parts[ 1 ] != protocol ||
643 parts[ 2 ] != loc.hostname ||
644 ( parts[ 3 ] || ( ( parts[ 1 ] || protocol ) === "http:" ? 80 : 443 ) ) !=
645 ( loc.port || ( protocol === "http:" ? 80 : 443 ) ) )
649 // Convert data if not already a string
650 if ( s.data && s.processData && typeof s.data !== "string" ) {
651 s.data = jQuery.param( s.data , s.traditional );
655 jQuery.ajaxPrefilter( s , options );
657 // Uppercase the type
658 s.type = s.type.toUpperCase();
660 // Determine if request has content
661 s.hasContent = ! rnoContent.test( s.type );
663 // Watch for a new set of requests
664 if ( s.global && jQuery.active++ === 0 ) {
665 jQuery.event.trigger( "ajaxStart" );
668 // More options handling for requests with no content
669 if ( ! s.hasContent ) {
671 // If data is available, append data to url
673 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
676 // Add anti-cache in url if needed
677 if ( s.cache === false ) {
679 var ts = jQuery.now(),
680 // try replacing _= if it is there
681 ret = s.url.replace( rts , "$1_=" + ts );
683 // if nothing was replaced, add timestamp to the end
684 s.url = ret + ( (ret == s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "");
688 // Set the correct header, if data is being sent
689 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
690 requestHeaders[ "content-type" ] = s.contentType;
693 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
694 if ( s.ifModified ) {
695 if ( jQuery_lastModified[ s.url ] ) {
696 requestHeaders[ "if-modified-since" ] = jQuery_lastModified[ s.url ];
698 if ( jQuery_etag[ s.url ] ) {
699 requestHeaders[ "if-none-match" ] = jQuery_etag[ s.url ];
703 // Set the Accepts header for the server, depending on the dataType
704 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
705 s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
708 // Check for headers option
709 for ( i in s.headers ) {
710 requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
713 // Allow custom headers/mimetypes and early abort
714 if ( s.beforeSend && ( s.beforeSend.call( callbackContext , jXHR , s ) === false || state === 2 ) ) {
716 // Abort if not done already
724 // Install callbacks on deferreds
725 for ( i in { success:1, error:1, complete:1 } ) {
730 transport = jQuery.ajaxTransport( s , options );
732 // If no transport, we auto-abort
735 done( 0 , "notransport" );
739 // Set state as sending
740 state = jXHR.readyState = 1;
744 globalEventContext.trigger( "ajaxSend" , [ jXHR , s ] );
748 if ( s.async && s.timeout > 0 ) {
749 timeoutTimer = setTimeout(function(){
750 jXHR.abort( "timeout" );
756 transport.send(requestHeaders, done);
758 // Propagate exception as error if not done
759 if ( status === 1 ) {
761 done(0, "error", "" + e);
764 // Simply rethrow otherwise
775 // Serialize an array of form elements or a set of
776 // key/values into a query string
777 param: function( a, traditional ) {
779 add = function( key, value ) {
780 // If value is a function, invoke it and return its value
781 value = jQuery.isFunction(value) ? value() : value;
782 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
785 // Set traditional to true for jQuery <= 1.3.2 behavior.
786 if ( traditional === undefined ) {
787 traditional = jQuery.ajaxSettings.traditional;
790 // If an array was passed in, assume that it is an array of form elements.
791 if ( jQuery.isArray(a) || a.jquery ) {
792 // Serialize the form elements
793 jQuery.each( a, function() {
794 add( this.name, this.value );
798 // If traditional, encode the "old" way (the way 1.3.2 or older
799 // did it), otherwise encode params recursively.
800 for ( var prefix in a ) {
801 buildParams( prefix, a[prefix], traditional, add );
805 // Return the resulting serialization
806 return s.join("&").replace(r20, "+");
810 function buildParams( prefix, obj, traditional, add ) {
811 if ( jQuery.isArray(obj) && obj.length ) {
812 // Serialize array item.
813 jQuery.each( obj, function( i, v ) {
814 if ( traditional || rbracket.test( prefix ) ) {
815 // Treat each array item as a scalar.
819 // If array item is non-scalar (array or object), encode its
820 // numeric index to resolve deserialization ambiguity issues.
821 // Note that rack (as of 1.0.0) can't currently deserialize
822 // nested arrays properly, and attempting to do so may cause
823 // a server error. Possible fixes are to modify rack's
824 // deserialization algorithm or to provide an option or flag
825 // to force array serialization to be shallow.
826 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
830 } else if ( !traditional && obj != null && typeof obj === "object" ) {
831 // If we see an array here, it is empty and should be treated as an empty
833 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
836 // Serialize object item.
838 jQuery.each( obj, function( k, v ) {
839 buildParams( prefix + "[" + k + "]", v, traditional, add );
844 // Serialize scalar item.
849 // This is still on the jQuery object... for now
850 // Want to move this to jQuery.ajax some day
853 // Counter for holding the number of active queries
856 // Last-Modified header cache for next request
862 // Base function for both ajaxPrefilter and ajaxTransport
863 function ajaxPrefilterOrTransport( arg0 , arg1 , arg2 ) {
865 var type = jQuery.type( arg1 ),
866 structure = jQuery.ajaxSettings[ arg0 ],
870 // We have an options map so we have to inspect the structure
871 if ( type === "object" ) {
874 originalOptions = arg2,
875 // When dealing with prefilters, we execute only
876 // (no selection so we never stop when a function
877 // returns a non-falsy, non-string value)
878 executeOnly = ( arg0 === "prefilters" ),
879 inspect = function( dataType, tested ) {
881 if ( ! tested[ dataType ] ) {
883 tested[ dataType ] = true;
885 var list = structure[ dataType ],
888 for( i = 0, length = list ? list.length : 0 ; ( executeOnly || ! selected ) && i < length ; i++ ) {
889 selected = list[ i ]( options , originalOptions );
890 // If we got redirected to a different dataType,
891 // we add it and switch to the corresponding list
892 if ( typeof( selected ) === "string" && selected !== dataType ) {
893 options.dataTypes.unshift( selected );
894 selected = inspect( selected , tested );
895 // We always break in order not to continue
896 // to iterate in previous list
900 // If we're only executing or nothing was selected
901 // we try the catchall dataType
902 if ( executeOnly || ! selected ) {
903 selected = inspect( "*" , tested );
905 // This will be ignored by ajaxPrefilter
906 // so it's safe to return no matter what
912 // Start inspection with current transport dataType
913 return inspect( options.dataTypes[ 0 ] , {} );
917 // We're requested to add to the structure
918 // Signature is ( dataTypeExpression , function )
919 // with dataTypeExpression being optional and
920 // defaulting to catchAll (*)
921 type = type === "function";
929 // We control that the second argument is really a function
930 if ( type || jQuery.isFunction( arg2 ) ) {
932 var dataTypes = arg1.split( /\s+/ ),
938 // For each dataType in the dataTypeExpression
939 for( i = 0 , length = dataTypes.length ; i < length ; i++ ) {
940 dataType = dataTypes[ i ];
941 // We control if we're asked to add before
942 // any existing element
943 placeBefore = /^\+/.test( dataType );
945 dataType = dataType.substr( 1 );
947 list = structure[ dataType ] = structure[ dataType ] || [];
948 // then we add to the structure accordingly
949 list[ placeBefore ? "unshift" : "push" ]( functor );