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 determineResponse: function( responses , ct ) {
241 contents = s.contents,
244 dataTypes = s.dataTypes,
245 transportDataType = dataTypes[0],
248 // Auto (xml, json, script or text determined given headers)
249 if ( ct && transportDataType === "*" ) {
251 for ( type in contents ) {
252 if ( ( regexp = contents[ type ] ) && regexp.test( ct ) ) {
253 transportDataType = dataTypes[0] = type;
260 for( type in responses ) {
261 if ( type === transportDataType ) {
266 // Get final response
267 response = responses[ type ];
269 // If it's not the right dataType, handle the dataTypeList
270 if ( transportDataType !== type ) {
271 if ( transportDataType === "*" ) {
274 dataTypes.unshift( type );
282 ajaxPrefilter: function( a , b ) {
283 ajaxPrefilterOrTransport( "prefilters" , a , b );
286 ajaxTransport: function( a , b ) {
287 return ajaxPrefilterOrTransport( "transports" , a , b );
291 ajax: function( url , options ) {
293 // If options is not an object,
294 // we simulate pre-1.5 signature
295 if ( typeof( options ) !== "object" ) {
300 // Force options to be an object
301 options = options || {};
303 var // Create the final options object
304 s = jQuery.extend( true , {} , jQuery.ajaxSettings , options ),
306 jQuery_lastModified = jQuery.lastModified,
307 jQuery_etag = jQuery.etag,
308 // Callbacks contexts
309 // We force the original context if it exists
310 // or take it from jQuery.ajaxSettings otherwise
311 // (plain objects used as context get extended)
313 ( s.context = ( "context" in options ? options : jQuery.ajaxSettings ).context ) || s,
314 globalEventContext = callbackContext === s ? jQuery.event : jQuery( callbackContext ),
316 deferred = jQuery.Deferred(),
317 completeDeferred = jQuery._Deferred(),
318 // Status-dependent callbacks
319 statusCode = s.statusCode || {},
320 // Headers (they are sent all at once)
323 responseHeadersString,
329 // Cross-domain detection vars
330 loc = document.location,
331 protocol = loc.protocol || "http:",
343 setRequestHeader: function(name,value) {
345 requestHeaders[ name.toLowerCase() ] = value;
351 getAllResponseHeaders: function() {
352 return state === 2 ? responseHeadersString : null;
355 // Builds headers hashtable if needed
356 getResponseHeader: function( key ) {
362 if ( !responseHeaders ) {
364 responseHeaders = {};
366 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
367 responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
370 match = responseHeaders[ key.toLowerCase() ];
374 return match || null;
377 // Cancel the request
378 abort: function( statusText ) {
380 transport.abort( statusText || "abort" );
382 done( 0 , statusText );
387 // Callback for when everything is done
388 // It is defined here because jslint complains if it is declared
389 // at the end of the function (which would be more logical and readable)
390 function done( status , statusText , response , headers) {
397 // State is "done" now
400 // Dereference transport for early garbage collection
401 // (no matter how long the jXHR transport will be used
402 transport = undefined;
405 jXHR.readyState = status ? 4 : 0;
407 // Cache response headers
408 responseHeadersString = headers || "";
410 // Clear timeout if it exists
411 if ( timeoutTimer ) {
412 clearTimeout(timeoutTimer);
417 // and ifModified status
418 ifModified = s.ifModified,
427 // To keep track of statusCode based callbacks
430 // If successful, handle type chaining
431 if ( status >= 200 && status < 300 || status === 304 ) {
433 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
434 if ( s.ifModified ) {
436 var lastModified = jXHR.getResponseHeader("Last-Modified"),
437 etag = jXHR.getResponseHeader("Etag");
440 jQuery_lastModified[ s.url ] = lastModified;
443 jQuery_etag[ s.url ] = etag;
448 if ( status === 304 ) {
450 // Set the statusText accordingly
451 statusText = "notmodified";
458 // Set the statusText accordingly
459 statusText = "success";
461 // Chain data conversions and determine the final value
462 // (if an exception is thrown in the process, it'll be notified as an error)
470 // Conversion expression
472 // Conversion function
474 // Conversion functions (when text is used in-between)
477 // Local references to dataTypes & converters
478 dataTypes = s.dataTypes,
479 converters = s.converters,
480 // DataType to responseXXX field mapping
486 // For each dataType in the chain
487 for( i = 0 ; i < dataTypes.length ; i++ ) {
489 current = dataTypes[ i ];
491 // If a responseXXX field for this dataType exists
492 // and if it hasn't been set yet
493 if ( responses[ current ] ) {
495 jXHR[ "response" + responses[ current ] ] = response;
497 responses[ current ] = 0;
500 // If this is not the first element
503 // Get the dataType to convert from
504 prev = dataTypes[ i - 1 ];
506 // If no catch-all and dataTypes are actually different
507 if ( prev !== "*" && current !== "*" && prev !== current ) {
510 conversion = prev + " " + current;
511 conv = converters[ conversion ] || converters[ "* " + current ];
515 // If there is no direct converter and none of the dataTypes is text
516 if ( ! conv && prev !== "text" && current !== "text" ) {
517 // Try with text in-between
518 conv1 = converters[ prev + " text" ] || converters[ "* text" ];
519 conv2 = converters[ "text " + current ];
520 // Revert back to a single converter
521 // if one of the converter is an equivalence
522 if ( conv1 === true ) {
524 } else if ( conv2 === true ) {
528 // If we found no converter, dispatch an error
529 if ( ! ( conv || conv1 && conv2 ) ) {
532 // If found converter is not an equivalence
533 if ( conv !== true ) {
534 // Convert with 1 or 2 converters accordingly
535 response = conv ? conv( response ) : conv2( conv1( response ) );
538 // If it is the first element of the chain
539 // and we have a dataFilter
540 } else if ( s.dataFilter ) {
541 // Apply the dataFilter
542 response = s.dataFilter( response , current );
543 // Get dataTypes again in case the filter changed them
544 dataTypes = s.dataTypes;
549 // We have a real success
553 // If an exception was thrown
556 // We have a parsererror
557 statusText = "parsererror";
563 // if not success, mark it as an error
566 error = statusText = statusText || "error";
568 // Set responseText if needed
570 jXHR.responseText = response;
574 // Set data for the fake xhr object
575 jXHR.status = status;
576 jXHR.statusText = statusText;
580 deferred.resolveWith( callbackContext , [ success , statusText , jXHR ] );
582 deferred.rejectWith( callbackContext , [ jXHR , statusText , error ] );
585 // Status-dependent callbacks
586 oldStatusCode = statusCode;
587 statusCode = undefined;
588 jXHR.statusCode( oldStatusCode );
591 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ) ,
592 [ jXHR , s , isSuccess ? success : error ] );
596 completeDeferred.resolveWith( callbackContext, [ jXHR , statusText ] );
599 globalEventContext.trigger( "ajaxComplete" , [ jXHR , s] );
600 // Handle the global AJAX counter
601 if ( ! --jQuery.active ) {
602 jQuery.event.trigger( "ajaxStop" );
608 deferred.promise( jXHR );
609 jXHR.success = jXHR.done;
610 jXHR.error = jXHR.fail;
611 jXHR.complete = completeDeferred.done;
613 // Status-dependent callbacks
614 jXHR.statusCode = function( map ) {
619 statusCode[ tmp ] = [ statusCode[ tmp ] , map[ tmp ] ];
622 tmp = map[ jXHR.status ];
623 jXHR.done( tmp ).fail( tmp );
629 // Remove hash character (#7531: and string promotion)
630 // We also use the url parameter if available
631 s.url = ( "" + ( url || s.url ) ).replace( rhash , "" );
633 // Extract dataTypes list
634 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( /\s+/ );
636 // Determine if a cross-domain request is in order
637 if ( ! s.crossDomain ) {
638 parts = rurl.exec( s.url.toLowerCase() );
641 ( parts[ 1 ] && parts[ 1 ] != protocol ||
642 parts[ 2 ] != loc.hostname ||
643 ( parts[ 3 ] || ( ( parts[ 1 ] || protocol ) === "http:" ? 80 : 443 ) ) !=
644 ( loc.port || ( protocol === "http:" ? 80 : 443 ) ) )
648 // Convert data if not already a string
649 if ( s.data && s.processData && typeof s.data !== "string" ) {
650 s.data = jQuery.param( s.data , s.traditional );
654 jQuery.ajaxPrefilter( s , options );
656 // Uppercase the type
657 s.type = s.type.toUpperCase();
659 // Determine if request has content
660 s.hasContent = ! rnoContent.test( s.type );
662 // Watch for a new set of requests
663 if ( s.global && jQuery.active++ === 0 ) {
664 jQuery.event.trigger( "ajaxStart" );
667 // More options handling for requests with no content
668 if ( ! s.hasContent ) {
670 // If data is available, append data to url
672 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
675 // Add anti-cache in url if needed
676 if ( s.cache === false ) {
678 var ts = jQuery.now(),
679 // try replacing _= if it is there
680 ret = s.url.replace( rts , "$1_=" + ts );
682 // if nothing was replaced, add timestamp to the end
683 s.url = ret + ( (ret == s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "");
687 // Set the correct header, if data is being sent
688 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
689 requestHeaders[ "content-type" ] = s.contentType;
692 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
693 if ( s.ifModified ) {
694 if ( jQuery_lastModified[ s.url ] ) {
695 requestHeaders[ "if-modified-since" ] = jQuery_lastModified[ s.url ];
697 if ( jQuery_etag[ s.url ] ) {
698 requestHeaders[ "if-none-match" ] = jQuery_etag[ s.url ];
702 // Set the Accepts header for the server, depending on the dataType
703 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
704 s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
707 // Check for headers option
708 for ( i in s.headers ) {
709 requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
712 // Allow custom headers/mimetypes and early abort
713 if ( s.beforeSend && ( s.beforeSend.call( callbackContext , jXHR , s ) === false || state === 2 ) ) {
715 // Abort if not done already
723 // Install callbacks on deferreds
724 for ( i in { success:1, error:1, complete:1 } ) {
729 transport = jQuery.ajaxTransport( s , options );
731 // If no transport, we auto-abort
734 done( 0 , "notransport" );
738 // Set state as sending
739 state = jXHR.readyState = 1;
743 globalEventContext.trigger( "ajaxSend" , [ jXHR , s ] );
747 if ( s.async && s.timeout > 0 ) {
748 timeoutTimer = setTimeout(function(){
749 jXHR.abort( "timeout" );
755 transport.send(requestHeaders, done);
757 // Propagate exception as error if not done
758 if ( status === 1 ) {
760 done(0, "error", "" + e);
763 // Simply rethrow otherwise
774 // Serialize an array of form elements or a set of
775 // key/values into a query string
776 param: function( a, traditional ) {
778 add = function( key, value ) {
779 // If value is a function, invoke it and return its value
780 value = jQuery.isFunction(value) ? value() : value;
781 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
784 // Set traditional to true for jQuery <= 1.3.2 behavior.
785 if ( traditional === undefined ) {
786 traditional = jQuery.ajaxSettings.traditional;
789 // If an array was passed in, assume that it is an array of form elements.
790 if ( jQuery.isArray(a) || a.jquery ) {
791 // Serialize the form elements
792 jQuery.each( a, function() {
793 add( this.name, this.value );
797 // If traditional, encode the "old" way (the way 1.3.2 or older
798 // did it), otherwise encode params recursively.
799 for ( var prefix in a ) {
800 buildParams( prefix, a[prefix], traditional, add );
804 // Return the resulting serialization
805 return s.join("&").replace(r20, "+");
809 function buildParams( prefix, obj, traditional, add ) {
810 if ( jQuery.isArray(obj) && obj.length ) {
811 // Serialize array item.
812 jQuery.each( obj, function( i, v ) {
813 if ( traditional || rbracket.test( prefix ) ) {
814 // Treat each array item as a scalar.
818 // If array item is non-scalar (array or object), encode its
819 // numeric index to resolve deserialization ambiguity issues.
820 // Note that rack (as of 1.0.0) can't currently deserialize
821 // nested arrays properly, and attempting to do so may cause
822 // a server error. Possible fixes are to modify rack's
823 // deserialization algorithm or to provide an option or flag
824 // to force array serialization to be shallow.
825 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
829 } else if ( !traditional && obj != null && typeof obj === "object" ) {
830 // If we see an array here, it is empty and should be treated as an empty
832 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
835 // Serialize object item.
837 jQuery.each( obj, function( k, v ) {
838 buildParams( prefix + "[" + k + "]", v, traditional, add );
843 // Serialize scalar item.
848 // This is still on the jQuery object... for now
849 // Want to move this to jQuery.ajax some day
852 // Counter for holding the number of active queries
855 // Last-Modified header cache for next request
861 // Base function for both ajaxPrefilter and ajaxTransport
862 function ajaxPrefilterOrTransport( arg0 , arg1 , arg2 ) {
864 var type = jQuery.type( arg1 ),
865 structure = jQuery.ajaxSettings[ arg0 ],
869 // We have an options map so we have to inspect the structure
870 if ( type === "object" ) {
873 originalOptions = arg2,
874 // When dealing with prefilters, we execute only
875 // (no selection so we never stop when a function
876 // returns a non-falsy, non-string value)
877 executeOnly = ( arg0 === "prefilters" ),
878 inspect = function( dataType, tested ) {
880 if ( ! tested[ dataType ] ) {
882 tested[ dataType ] = true;
884 var list = structure[ dataType ],
887 for( i = 0, length = list ? list.length : 0 ; ( executeOnly || ! selected ) && i < length ; i++ ) {
888 selected = list[ i ]( options , originalOptions );
889 // If we got redirected to a different dataType,
890 // we add it and switch to the corresponding list
891 if ( typeof( selected ) === "string" && selected !== dataType ) {
892 options.dataTypes.unshift( selected );
893 selected = inspect( selected , tested );
894 // We always break in order not to continue
895 // to iterate in previous list
899 // If we're only executing or nothing was selected
900 // we try the catchall dataType
901 if ( executeOnly || ! selected ) {
902 selected = inspect( "*" , tested );
904 // This will be ignored by ajaxPrefilter
905 // so it's safe to return no matter what
911 // Start inspection with current transport dataType
912 return inspect( options.dataTypes[ 0 ] , {} );
916 // We're requested to add to the structure
917 // Signature is ( dataTypeExpression , function )
918 // with dataTypeExpression being optional and
919 // defaulting to catchAll (*)
920 type = type === "function";
928 // We control that the second argument is really a function
929 if ( type || jQuery.isFunction( arg2 ) ) {
931 var dataTypes = arg1.split( /\s+/ ),
937 // For each dataType in the dataTypeExpression
938 for( i = 0 , length = dataTypes.length ; i < length ; i++ ) {
939 dataType = dataTypes[ i ];
940 // We control if we're asked to add before
941 // any existing element
942 placeBefore = /^\+/.test( dataType );
944 dataType = dataType.substr( 1 );
946 list = structure[ dataType ] = structure[ dataType ] || [];
947 // then we add to the structure accordingly
948 list[ placeBefore ? "unshift" : "push" ]( functor );