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 );
171 contentType: "application/x-www-form-urlencoded",
187 xml: "application/xml, text/xml",
190 json: "application/json, text/javascript",
201 // 1) They are useful to introduce custom dataTypes (see transport/jsonp for an example)
202 // 2) These are called:
203 // * BEFORE asking for a transport
204 // * AFTER param serialization (s.data is a string if s.processData is true)
205 // 3) key is the dataType
206 // 4) the catchall symbol "*" can be used
207 // 5) execution will start with transport dataType and THEN continue down to "*" if needed
210 // Transports bindings
211 // 1) key is the dataType
212 // 2) the catchall symbol "*" can be used
213 // 3) selection will start with transport dataType and THEN go to "*" if needed
216 // List of data converters
217 // 1) key format is "source_type destination_type" (a single space in-between)
218 // 2) the catchall symbol "*" can be used for source_type
221 // Convert anything to text
222 "* text": window.String,
224 // Text to html (true = no transformation)
227 // Evaluate text as a json expression
228 "text json": jQuery.parseJSON,
231 "text xml": jQuery.parseXML
236 ajax: function( url , options ) {
239 if ( arguments.length === 1 ) {
241 url = options ? options.url : undefined;
244 // Force options to be an object
245 options = options || {};
247 // Get the url if provided separately
248 options.url = url || options.url;
250 var // Create the final options object
251 s = jQuery.extend( true , {} , jQuery.ajaxSettings , options ),
253 jQuery_lastModified = jQuery.lastModified,
254 jQuery_etag = jQuery.etag,
255 // Callbacks contexts
256 callbackContext = options.context || s.context || s,
257 globalEventContext = callbackContext === s ? jQuery.event : jQuery( callbackContext ),
259 deferred = jQuery.Deferred(),
260 completeDeferred = jQuery._Deferred(),
261 // Status-dependent callbacks
262 statusCode = s.statusCode || {},
263 // Headers (they are sent all at once)
266 responseHeadersString,
272 // Cross-domain detection vars
273 loc = document.location,
285 setRequestHeader: function(name,value) {
287 requestHeaders[ name.toLowerCase() ] = value;
293 getAllResponseHeaders: function() {
294 return state === 2 ? responseHeadersString : null;
297 // Builds headers hashtable if needed
298 getResponseHeader: function( key ) {
304 if ( !responseHeaders ) {
306 responseHeaders = {};
308 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
309 responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
312 match = responseHeaders[ key.toLowerCase() ];
316 return match || null;
319 // Cancel the request
320 abort: function( statusText ) {
322 transport.abort( statusText || "abort" );
324 done( 0 , statusText );
329 // We force the original context
330 // (plain objects used as context get extended)
331 s.context = options.context;
333 // Callback for when everything is done
334 // It is defined here because jslint complains if it is declared
335 // at the end of the function (which would be more logical and readable)
336 function done( status , statusText , response , headers) {
343 // State is "done" now
346 // Dereference transport for early garbage collection
347 // (no matter how long the jXHR transport will be used
348 transport = undefined;
351 jXHR.readyState = status ? 4 : 0;
353 // Cache response headers
354 responseHeadersString = headers || "";
356 // Clear timeout if it exists
357 if ( timeoutTimer ) {
358 clearTimeout(timeoutTimer);
363 // and ifModified status
364 ifModified = s.ifModified,
373 // If successful, handle type chaining
374 if ( status >= 200 && status < 300 || status === 304 ) {
376 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
377 if ( s.ifModified ) {
379 var lastModified = jXHR.getResponseHeader("Last-Modified"),
380 etag = jXHR.getResponseHeader("Etag");
383 jQuery_lastModified[ s.url ] = lastModified;
386 jQuery_etag[ s.url ] = etag;
391 if ( status === 304 ) {
393 // Set the statusText accordingly
394 statusText = "notmodified";
401 // Set the statusText accordingly
402 statusText = "success";
404 // Chain data conversions and determine the final value
405 // (if an exception is thrown in the process, it'll be notified as an error)
413 // Conversion function
415 // Conversion functions (when text is used in-between)
418 // Local references to dataTypes & converters
419 dataTypes = s.dataTypes,
420 converters = s.converters,
421 // DataType to responseXXX field mapping
427 // For each dataType in the chain
428 for( i = 0 ; i < dataTypes.length ; i++ ) {
430 current = dataTypes[ i ];
432 // If a responseXXX field for this dataType exists
433 // and if it hasn't been set yet
434 if ( responses[ current ] ) {
436 jXHR[ "response" + responses[ current ] ] = response;
438 responses[ current ] = 0;
441 // If this is not the first element
444 // Get the dataType to convert from
445 prev = dataTypes[ i - 1 ];
447 // If no catch-all and dataTypes are actually different
448 if ( prev !== "*" && current !== "*" && prev !== current ) {
451 conv = converters[ prev + " " + current ] ||
452 converters[ "* " + current ];
456 // If there is no direct converter and none of the dataTypes is text
457 if ( ! conv && prev !== "text" && current !== "text" ) {
458 // Try with text in-between
459 conv1 = converters[ prev + " text" ] || converters[ "* text" ];
460 conv2 = converters[ "text " + current ];
461 // Revert back to a single converter
462 // if one of the converter is an equivalence
463 if ( conv1 === true ) {
465 } else if ( conv2 === true ) {
469 // If we found no converter, dispatch an error
470 if ( ! ( conv || conv1 && conv2 ) ) {
473 // If found converter is not an equivalence
474 if ( conv !== true ) {
475 // Convert with 1 or 2 converters accordingly
476 response = conv ? conv( response ) : conv2( conv1( response ) );
479 // If it is the first element of the chain
480 // and we have a dataFilter
481 } else if ( s.dataFilter ) {
482 // Apply the dataFilter
483 response = s.dataFilter( response , current );
484 // Get dataTypes again in case the filter changed them
485 dataTypes = s.dataTypes;
490 // We have a real success
494 // If an exception was thrown
497 // We have a parsererror
498 statusText = "parsererror";
504 // if not success, mark it as an error
507 error = statusText = statusText || "error";
509 // Set responseText if needed
511 jXHR.responseText = response;
515 // Set data for the fake xhr object
516 jXHR.status = status;
517 jXHR.statusText = statusText;
521 deferred.fire( callbackContext , [ success , statusText , jXHR ] );
523 deferred.fireReject( callbackContext , [ jXHR , statusText , error ] );
526 // Status-dependent callbacks
527 jXHR.statusCode( statusCode );
530 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ) ,
531 [ jXHR , s , isSuccess ? success : error ] );
535 completeDeferred.fire( callbackContext, [ jXHR , statusText ] );
538 globalEventContext.trigger( "ajaxComplete" , [ jXHR , s] );
539 // Handle the global AJAX counter
540 if ( ! --jQuery.active ) {
541 jQuery.event.trigger( "ajaxStop" );
547 deferred.promise( jXHR );
548 jXHR.success = jXHR.done;
549 jXHR.error = jXHR.fail;
550 jXHR.complete = completeDeferred.done;
552 // Status-dependent callbacks
553 jXHR.statusCode = function( map ) {
555 var resolved = jXHR.isResolved(),
557 if ( resolved || jXHR.isRejected() ) {
558 tmp = map[ jXHR.status ];
560 if ( map === statusCode ) {
561 delete statusCode[ jXHR.status ];
563 jXHR[ resolved ? "done" : "fail" ]( tmp );
567 statusCode[ tmp ] = [ statusCode[ tmp ] , map[ tmp ] ];
574 // Remove hash character (#7531: and string promotion)
575 s.url = ( "" + s.url ).replace( rhash , "" );
577 // Extract dataTypes list
578 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( /\s+/ );
580 // Determine if a cross-domain request is in order
581 if ( ! s.crossDomain ) {
582 parts = rurl.exec( s.url.toLowerCase() );
585 ( parts[ 1 ] && parts[ 1 ] != loc.protocol ||
586 parts[ 2 ] != loc.hostname ||
587 ( parts[ 3 ] || 80 ) != ( loc.port || 80 ) )
591 // Convert data if not already a string
592 if ( s.data && s.processData && typeof s.data !== "string" ) {
593 s.data = jQuery.param( s.data , s.traditional );
597 jQuery.ajaxPrefilter( s , options );
599 // Uppercase the type
600 s.type = s.type.toUpperCase();
602 // Determine if request has content
603 s.hasContent = ! rnoContent.test( s.type );
605 // Watch for a new set of requests
606 if ( s.global && jQuery.active++ === 0 ) {
607 jQuery.event.trigger( "ajaxStart" );
610 // More options handling for requests with no content
611 if ( ! s.hasContent ) {
613 // If data is available, append data to url
615 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
618 // Add anti-cache in url if needed
619 if ( s.cache === false ) {
621 var ts = jQuery.now(),
622 // try replacing _= if it is there
623 ret = s.url.replace( rts , "$1_=" + ts );
625 // if nothing was replaced, add timestamp to the end
626 s.url = ret + ( (ret == s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "");
630 // Set the correct header, if data is being sent
631 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
632 requestHeaders[ "content-type" ] = s.contentType;
635 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
636 if ( s.ifModified ) {
637 if ( jQuery_lastModified[ s.url ] ) {
638 requestHeaders[ "if-modified-since" ] = jQuery_lastModified[ s.url ];
640 if ( jQuery_etag[ s.url ] ) {
641 requestHeaders[ "if-none-match" ] = jQuery_etag[ s.url ];
645 // Set the Accepts header for the server, depending on the dataType
646 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
647 s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
650 // Check for headers option
651 for ( i in s.headers ) {
652 requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
655 // Allow custom headers/mimetypes and early abort
656 if ( s.beforeSend && ( s.beforeSend.call( callbackContext , jXHR , s ) === false || state === 2 ) ) {
658 // Abort if not done already
666 // Install callbacks on deferreds
667 for ( i in { success:1, error:1, complete:1 } ) {
672 transport = jQuery.ajaxTransport( s );
674 // If no transport, we auto-abort
677 done( 0 , "notransport" );
681 // Set state as sending
682 state = jXHR.readyState = 1;
686 globalEventContext.trigger( "ajaxSend" , [ jXHR , s ] );
690 if ( s.async && s.timeout > 0 ) {
691 timeoutTimer = setTimeout(function(){
692 jXHR.abort( "timeout" );
698 transport.send(requestHeaders, done);
700 // Propagate exception as error if not done
701 if ( status === 1 ) {
703 done(0, "error", "" + e);
706 // Simply rethrow otherwise
717 // Serialize an array of form elements or a set of
718 // key/values into a query string
719 param: function( a, traditional ) {
721 add = function( key, value ) {
722 // If value is a function, invoke it and return its value
723 value = jQuery.isFunction(value) ? value() : value;
724 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
727 // Set traditional to true for jQuery <= 1.3.2 behavior.
728 if ( traditional === undefined ) {
729 traditional = jQuery.ajaxSettings.traditional;
732 // If an array was passed in, assume that it is an array of form elements.
733 if ( jQuery.isArray(a) || a.jquery ) {
734 // Serialize the form elements
735 jQuery.each( a, function() {
736 add( this.name, this.value );
740 // If traditional, encode the "old" way (the way 1.3.2 or older
741 // did it), otherwise encode params recursively.
742 for ( var prefix in a ) {
743 buildParams( prefix, a[prefix], traditional, add );
747 // Return the resulting serialization
748 return s.join("&").replace(r20, "+");
752 function buildParams( prefix, obj, traditional, add ) {
753 if ( jQuery.isArray(obj) && obj.length ) {
754 // Serialize array item.
755 jQuery.each( obj, function( i, v ) {
756 if ( traditional || rbracket.test( prefix ) ) {
757 // Treat each array item as a scalar.
761 // If array item is non-scalar (array or object), encode its
762 // numeric index to resolve deserialization ambiguity issues.
763 // Note that rack (as of 1.0.0) can't currently deserialize
764 // nested arrays properly, and attempting to do so may cause
765 // a server error. Possible fixes are to modify rack's
766 // deserialization algorithm or to provide an option or flag
767 // to force array serialization to be shallow.
768 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
772 } else if ( !traditional && obj != null && typeof obj === "object" ) {
773 // If we see an array here, it is empty and should be treated as an empty
775 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
778 // Serialize object item.
780 jQuery.each( obj, function( k, v ) {
781 buildParams( prefix + "[" + k + "]", v, traditional, add );
786 // Serialize scalar item.
791 // This is still on the jQuery object... for now
792 // Want to move this to jQuery.ajax some day
795 // Counter for holding the number of active queries
798 // Last-Modified header cache for next request
804 //Execute or select from functions in a given structure of options
805 function ajax_selectOrExecute( structure , s ) {
807 var dataTypes = s.dataTypes,
815 noSelect = structure !== "transports";
817 function initSearch( dataType ) {
819 flag = transportDataType !== dataType && ! checked[ dataType ];
823 checked[ dataType ] = 1;
824 transportDataType = dataType;
825 list = s[ structure ][ dataType ];
827 length = list ? list.length : 0 ;
833 initSearch( dataTypes[ 0 ] );
835 for ( i = 0 ; ( noSelect || ! selected ) && i <= length ; i++ ) {
837 if ( i === length ) {
843 selected = list[ i ]( s , determineDataType );
845 // If we got redirected to another dataType
846 // Search there (if not in progress or already tried)
847 if ( typeof( selected ) === "string" &&
848 initSearch( selected ) ) {
850 dataTypes.unshift( selected );
856 return noSelect ? jQuery : selected;
859 // Add an element to one of the structures in ajaxSettings
860 function ajax_addElement( structure , args ) {
864 length = args.length,
875 first = jQuery.type( args[ 0 ] );
877 if ( first === "object" ) {
878 return ajax_selectOrExecute( structure , args[ 0 ] );
881 structure = jQuery.ajaxSettings[ structure ];
883 if ( first !== "function" ) {
885 dataTypes = args[ 0 ].toLowerCase().split(/\s+/);
886 dLength = dataTypes.length;
891 if ( dLength && start < length ) {
893 functors = sliceFunc.call( args , start );
895 for( i = 0 ; i < dLength ; i++ ) {
897 dataType = dataTypes[ i ];
899 first = /^\+/.test( dataType );
902 dataType = dataType.substr(1);
905 if ( dataType !== "" ) {
907 append = Array.prototype[ first ? "unshift" : "push" ];
908 list = structure[ dataType ] = structure[ dataType ] || [];
909 append.apply( list , functors );
918 // Install prefilter & transport methods
919 jQuery.each( [ "Prefilter" , "Transport" ] , function( _ , name ) {
920 _ = name.toLowerCase() + "s";
921 jQuery[ "ajax" + name ] = function() {
922 return ajax_addElement( _ , arguments );
926 // Utility function that handles dataType when response is received
927 // (for those transports that can give text or xml responses)
928 function determineDataType( s , ct , text , xml ) {
930 var contents = s.contents,
933 dataTypes = s.dataTypes,
934 transportDataType = dataTypes[0],
937 // Auto (xml, json, script or text determined given headers)
938 if ( transportDataType === "*" ) {
940 for ( type in contents ) {
941 if ( ( regexp = contents[ type ] ) && regexp.test( ct ) ) {
942 transportDataType = dataTypes[0] = type;
948 // xml and parsed as such
949 if ( transportDataType === "xml" &&
951 xml.documentElement /* #4958 */ ) {
955 // Text response was provided
960 // If it's not really text, defer to converters
961 if ( transportDataType !== "text" ) {
962 dataTypes.unshift( "text" );