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",
208 // 1) They are useful to introduce custom dataTypes (see transport/jsonp for an example)
209 // 2) These are called:
210 // * BEFORE asking for a transport
211 // * AFTER param serialization (s.data is a string if s.processData is true)
212 // 3) key is the dataType
213 // 4) the catchall symbol "*" can be used
214 // 5) execution will start with transport dataType and THEN continue down to "*" if needed
217 // Transports bindings
218 // 1) key is the dataType
219 // 2) the catchall symbol "*" can be used
220 // 3) selection will start with transport dataType and THEN go to "*" if needed
223 // List of data converters
224 // 1) key format is "source_type destination_type" (a single space in-between)
225 // 2) the catchall symbol "*" can be used for source_type
228 // Convert anything to text
229 "* text": window.String,
231 // Text to html (true = no transformation)
234 // Evaluate text as a json expression
235 "text json": jQuery.parseJSON,
238 "text xml": jQuery.parseXML
242 ajaxPrefilter: function( a , b ) {
243 ajaxPrefilterOrTransport( "prefilters" , a , b );
246 ajaxTransport: function( a , b ) {
247 return ajaxPrefilterOrTransport( "transports" , a , b );
251 ajax: function( url , options ) {
253 // If options is not an object,
254 // we simulate pre-1.5 signature
255 if ( typeof( options ) !== "object" ) {
260 // Force options to be an object
261 options = options || {};
263 var // Create the final options object
264 s = jQuery.extend( true , {} , jQuery.ajaxSettings , options ),
266 jQuery_lastModified = jQuery.lastModified,
267 jQuery_etag = jQuery.etag,
268 // Callbacks contexts
269 // We force the original context if it exists
270 // or take it from jQuery.ajaxSettings otherwise
271 // (plain objects used as context get extended)
273 ( s.context = ( "context" in options ? options : jQuery.ajaxSettings ).context ) || s,
274 globalEventContext = callbackContext === s ? jQuery.event : jQuery( callbackContext ),
276 deferred = jQuery.Deferred(),
277 completeDeferred = jQuery._Deferred(),
278 // Status-dependent callbacks
279 statusCode = s.statusCode || {},
280 // Headers (they are sent all at once)
283 responseHeadersString,
289 // Cross-domain detection vars
290 loc = document.location,
291 protocol = loc.protocol || "http:",
303 setRequestHeader: function(name,value) {
305 requestHeaders[ name.toLowerCase() ] = value;
311 getAllResponseHeaders: function() {
312 return state === 2 ? responseHeadersString : null;
315 // Builds headers hashtable if needed
316 getResponseHeader: function( key ) {
322 if ( !responseHeaders ) {
324 responseHeaders = {};
326 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
327 responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
330 match = responseHeaders[ key.toLowerCase() ];
334 return match || null;
337 // Cancel the request
338 abort: function( statusText ) {
340 transport.abort( statusText || "abort" );
342 done( 0 , statusText );
347 // Callback for when everything is done
348 // It is defined here because jslint complains if it is declared
349 // at the end of the function (which would be more logical and readable)
350 function done( status , statusText , responses , headers) {
357 // State is "done" now
360 // Dereference transport for early garbage collection
361 // (no matter how long the jXHR object will be used)
362 transport = undefined;
365 jXHR.readyState = status ? 4 : 0;
367 // Cache response headers
368 responseHeadersString = headers || "";
370 // Clear timeout if it exists
371 if ( timeoutTimer ) {
372 clearTimeout(timeoutTimer);
375 var // Reference dataTypes and responseFields
376 dataTypes = s.dataTypes,
377 responseFields = s.responseFields,
380 // Flag to mark as success
387 // To keep track of statusCode based callbacks
393 // If we got responses:
394 // - find the right one
395 // - update dataTypes accordingly
396 // - set responseXXX accordingly too
399 var contents = s.contents,
400 transportDataType = dataTypes[0],
405 // Auto (xml, json, script or text determined given headers)
406 if ( transportDataType === "*" && ( ct = jXHR.getResponseHeader( "content-type" ) ) ) {
408 for ( type in contents ) {
409 if ( contents[ type ] && contents[ type ].test( ct ) ) {
410 transportDataType = dataTypes[0] = type;
418 // Get final dataType
419 for( type in responses ) {
420 if ( ! finalDataType && type === transportDataType ) {
421 finalDataType = type;
423 responseField = responseFields[ type ];
424 if ( responseField && ! ( responseField in jXHR ) ) {
425 jXHR[ responseField ] = responses[ type ];
429 // If no response with the expected dataType was provided
430 // Take the last response as a default if it exists
431 if ( ! finalDataType && type ) {
432 finalDataType = type;
433 if ( transportDataType === "*" ) {
436 dataTypes.unshift( finalDataType );
439 // Get final response
440 response = responses[ finalDataType ];
443 // If successful, handle type chaining
444 if ( status >= 200 && status < 300 || status === 304 ) {
446 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
447 if ( s.ifModified ) {
449 var lastModified = jXHR.getResponseHeader("Last-Modified"),
450 etag = jXHR.getResponseHeader("Etag");
453 jQuery_lastModified[ s.url ] = lastModified;
456 jQuery_etag[ s.url ] = etag;
461 if ( status === 304 ) {
463 statusText = "notmodified";
469 statusText = "success";
471 // Chain data conversions and determine the final value
472 // (if an exception is thrown in the process, it'll be notified as an error)
480 // Conversion expression
482 // Conversion function
484 // Conversion functions (when text is used in-between)
487 // Local references to converters
488 converters = s.converters;
490 // For each dataType in the chain
491 for( i = 0 ; i < dataTypes.length ; i++ ) {
493 current = dataTypes[ i ];
495 // If a responseXXX field for this dataType exists
496 // and if it hasn't been set yet
497 responseField = responseFields[ current ];
498 if ( responseField && ! ( responseField in jXHR ) ) {
499 jXHR[ responseField ] = response;
502 // If this is not the first element
505 // Get the dataType to convert from
506 prev = dataTypes[ i - 1 ];
508 // If no catch-all and dataTypes are actually different
509 if ( prev !== "*" && current !== "*" && prev !== current ) {
512 conversion = prev + " " + current;
513 conv = converters[ conversion ] || converters[ "* " + current ];
517 // If there is no direct converter and none of the dataTypes is text
518 if ( ! conv && prev !== "text" && current !== "text" ) {
519 // Try with text in-between
520 conv1 = converters[ prev + " text" ] || converters[ "* text" ];
521 conv2 = converters[ "text " + current ];
522 // Revert back to a single converter
523 // if one of the converter is an equivalence
524 if ( conv1 === true ) {
526 } else if ( conv2 === true ) {
530 // If we found no converter, dispatch an error
531 if ( ! ( conv || conv1 && conv2 ) ) {
534 // If found converter is not an equivalence
535 if ( conv !== true ) {
536 // Convert with 1 or 2 converters accordingly
537 response = conv ? conv( response ) : conv2( conv1( response ) );
540 // If it is the first element of the chain
541 // and we have a dataFilter
542 } else if ( s.dataFilter ) {
543 // Apply the dataFilter
544 response = s.dataFilter( response , current );
545 // Get dataTypes again in case the filter changed them
546 dataTypes = s.dataTypes;
551 // We have a real success
555 // If an exception was thrown
558 // We have a parsererror
559 statusText = "parsererror";
565 // if not success, mark it as an error
567 error = statusText = statusText || "error";
570 // Set data for the fake xhr object
571 jXHR.status = status;
572 jXHR.statusText = statusText;
576 deferred.resolveWith( callbackContext , [ success , statusText , jXHR ] );
578 deferred.rejectWith( callbackContext , [ jXHR , statusText , error ] );
581 // Status-dependent callbacks
582 oldStatusCode = statusCode;
583 statusCode = undefined;
584 jXHR.statusCode( oldStatusCode );
587 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ) ,
588 [ jXHR , s , isSuccess ? success : error ] );
592 completeDeferred.resolveWith( callbackContext, [ jXHR , statusText ] );
595 globalEventContext.trigger( "ajaxComplete" , [ jXHR , s] );
596 // Handle the global AJAX counter
597 if ( ! --jQuery.active ) {
598 jQuery.event.trigger( "ajaxStop" );
604 deferred.promise( jXHR );
605 jXHR.success = jXHR.done;
606 jXHR.error = jXHR.fail;
607 jXHR.complete = completeDeferred.done;
609 // Status-dependent callbacks
610 jXHR.statusCode = function( map ) {
615 statusCode[ tmp ] = [ statusCode[ tmp ] , map[ tmp ] ];
618 tmp = map[ jXHR.status ];
619 jXHR.done( tmp ).fail( tmp );
625 // Remove hash character (#7531: and string promotion)
626 // We also use the url parameter if available
627 s.url = ( "" + ( url || s.url ) ).replace( rhash , "" );
629 // Extract dataTypes list
630 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( /\s+/ );
632 // Determine if a cross-domain request is in order
633 if ( ! s.crossDomain ) {
634 parts = rurl.exec( s.url.toLowerCase() );
637 ( parts[ 1 ] && parts[ 1 ] != protocol ||
638 parts[ 2 ] != loc.hostname ||
639 ( parts[ 3 ] || ( ( parts[ 1 ] || protocol ) === "http:" ? 80 : 443 ) ) !=
640 ( loc.port || ( protocol === "http:" ? 80 : 443 ) ) )
644 // Convert data if not already a string
645 if ( s.data && s.processData && typeof s.data !== "string" ) {
646 s.data = jQuery.param( s.data , s.traditional );
650 jQuery.ajaxPrefilter( s , options );
652 // Uppercase the type
653 s.type = s.type.toUpperCase();
655 // Determine if request has content
656 s.hasContent = ! rnoContent.test( s.type );
658 // Watch for a new set of requests
659 if ( s.global && jQuery.active++ === 0 ) {
660 jQuery.event.trigger( "ajaxStart" );
663 // More options handling for requests with no content
664 if ( ! s.hasContent ) {
666 // If data is available, append data to url
668 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
671 // Add anti-cache in url if needed
672 if ( s.cache === false ) {
674 var ts = jQuery.now(),
675 // try replacing _= if it is there
676 ret = s.url.replace( rts , "$1_=" + ts );
678 // if nothing was replaced, add timestamp to the end
679 s.url = ret + ( (ret == s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "");
683 // Set the correct header, if data is being sent
684 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
685 requestHeaders[ "content-type" ] = s.contentType;
688 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
689 if ( s.ifModified ) {
690 if ( jQuery_lastModified[ s.url ] ) {
691 requestHeaders[ "if-modified-since" ] = jQuery_lastModified[ s.url ];
693 if ( jQuery_etag[ s.url ] ) {
694 requestHeaders[ "if-none-match" ] = jQuery_etag[ s.url ];
698 // Set the Accepts header for the server, depending on the dataType
699 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
700 s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
703 // Check for headers option
704 for ( i in s.headers ) {
705 requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
708 // Allow custom headers/mimetypes and early abort
709 if ( s.beforeSend && ( s.beforeSend.call( callbackContext , jXHR , s ) === false || state === 2 ) ) {
711 // Abort if not done already
719 // Install callbacks on deferreds
720 for ( i in { success:1, error:1, complete:1 } ) {
725 transport = jQuery.ajaxTransport( s , options );
727 // If no transport, we auto-abort
730 done( 0 , "notransport" );
734 // Set state as sending
735 state = jXHR.readyState = 1;
739 globalEventContext.trigger( "ajaxSend" , [ jXHR , s ] );
743 if ( s.async && s.timeout > 0 ) {
744 timeoutTimer = setTimeout(function(){
745 jXHR.abort( "timeout" );
751 transport.send(requestHeaders, done);
753 // Propagate exception as error if not done
754 if ( status === 1 ) {
756 done(0, "error", "" + e);
759 // Simply rethrow otherwise
770 // Serialize an array of form elements or a set of
771 // key/values into a query string
772 param: function( a, traditional ) {
774 add = function( key, value ) {
775 // If value is a function, invoke it and return its value
776 value = jQuery.isFunction(value) ? value() : value;
777 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
780 // Set traditional to true for jQuery <= 1.3.2 behavior.
781 if ( traditional === undefined ) {
782 traditional = jQuery.ajaxSettings.traditional;
785 // If an array was passed in, assume that it is an array of form elements.
786 if ( jQuery.isArray(a) || a.jquery ) {
787 // Serialize the form elements
788 jQuery.each( a, function() {
789 add( this.name, this.value );
793 // If traditional, encode the "old" way (the way 1.3.2 or older
794 // did it), otherwise encode params recursively.
795 for ( var prefix in a ) {
796 buildParams( prefix, a[prefix], traditional, add );
800 // Return the resulting serialization
801 return s.join("&").replace(r20, "+");
805 function buildParams( prefix, obj, traditional, add ) {
806 if ( jQuery.isArray(obj) && obj.length ) {
807 // Serialize array item.
808 jQuery.each( obj, function( i, v ) {
809 if ( traditional || rbracket.test( prefix ) ) {
810 // Treat each array item as a scalar.
814 // If array item is non-scalar (array or object), encode its
815 // numeric index to resolve deserialization ambiguity issues.
816 // Note that rack (as of 1.0.0) can't currently deserialize
817 // nested arrays properly, and attempting to do so may cause
818 // a server error. Possible fixes are to modify rack's
819 // deserialization algorithm or to provide an option or flag
820 // to force array serialization to be shallow.
821 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
825 } else if ( !traditional && obj != null && typeof obj === "object" ) {
826 // If we see an array here, it is empty and should be treated as an empty
828 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
831 // Serialize object item.
833 jQuery.each( obj, function( k, v ) {
834 buildParams( prefix + "[" + k + "]", v, traditional, add );
839 // Serialize scalar item.
844 // This is still on the jQuery object... for now
845 // Want to move this to jQuery.ajax some day
848 // Counter for holding the number of active queries
851 // Last-Modified header cache for next request
857 // Base function for both ajaxPrefilter and ajaxTransport
858 function ajaxPrefilterOrTransport( arg0 , arg1 , arg2 ) {
860 var type = jQuery.type( arg1 ),
861 structure = jQuery.ajaxSettings[ arg0 ],
865 // We have an options map so we have to inspect the structure
866 if ( type === "object" ) {
869 originalOptions = arg2,
870 // When dealing with prefilters, we execute only
871 // (no selection so we never stop when a function
872 // returns a non-falsy, non-string value)
873 executeOnly = ( arg0 === "prefilters" ),
874 inspect = function( dataType, tested ) {
876 if ( ! tested[ dataType ] ) {
878 tested[ dataType ] = true;
880 var list = structure[ dataType ],
883 for( i = 0, length = list ? list.length : 0 ; ( executeOnly || ! selected ) && i < length ; i++ ) {
884 selected = list[ i ]( options , originalOptions );
885 // If we got redirected to a different dataType,
886 // we add it and switch to the corresponding list
887 if ( typeof( selected ) === "string" && selected !== dataType ) {
888 options.dataTypes.unshift( selected );
889 selected = inspect( selected , tested );
890 // We always break in order not to continue
891 // to iterate in previous list
895 // If we're only executing or nothing was selected
896 // we try the catchall dataType
897 if ( executeOnly || ! selected ) {
898 selected = inspect( "*" , tested );
900 // This will be ignored by ajaxPrefilter
901 // so it's safe to return no matter what
907 // Start inspection with current transport dataType
908 return inspect( options.dataTypes[ 0 ] , {} );
912 // We're requested to add to the structure
913 // Signature is ( dataTypeExpression , function )
914 // with dataTypeExpression being optional and
915 // defaulting to catchAll (*)
916 type = type === "function";
924 // We control that the second argument is really a function
925 if ( type || jQuery.isFunction( arg2 ) ) {
927 var dataTypes = arg1.split( /\s+/ ),
933 // For each dataType in the dataTypeExpression
934 for( i = 0 , length = dataTypes.length ; i < length ; i++ ) {
935 dataType = dataTypes[ i ];
936 // We control if we're asked to add before
937 // any existing element
938 placeBefore = /^\+/.test( dataType );
940 dataType = dataType.substr( 1 );
942 list = structure[ dataType ] = structure[ dataType ] || [];
943 // then we add to the structure accordingly
944 list[ placeBefore ? "unshift" : "push" ]( functor );