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 );
170 contentType: "application/x-www-form-urlencoded",
184 return new window.XMLHttpRequest();
188 xml: "application/xml, text/xml",
191 json: "application/json, text/javascript",
202 // 1) They are useful to introduce custom dataTypes (see transport/jsonp for an example)
203 // 2) These are called:
204 // * BEFORE asking for a transport
205 // * AFTER param serialization (s.data is a string if s.processData is true)
206 // 3) key is the dataType
207 // 4) the catchall symbol "*" can be used
208 // 5) execution will start with transport dataType and THEN continue down to "*" if needed
211 // Transports bindings
212 // 1) key is the dataType
213 // 2) the catchall symbol "*" can be used
214 // 3) selection will start with transport dataType and THEN go to "*" if needed
217 // List of data converters
218 // 1) key format is "source_type destination_type" (a single space in-between)
219 // 2) the catchall symbol "*" can be used for source_type
222 // Convert anything to text
223 "* text": window.String,
225 // Text to html (true = no transformation)
228 // Evaluate text as a json expression
229 "text json": jQuery.parseJSON,
232 "text xml": jQuery.parseXML
237 // (s is used internally)
238 ajax: function( url , options , s ) {
241 if ( arguments.length === 1 ) {
243 url = options ? options.url : undefined;
246 // Force options to be an object
247 options = options || {};
249 // Get the url if provided separately
250 options.url = url || options.url;
252 // Create the final options object
253 s = jQuery.extend( true , {} , jQuery.ajaxSettings , options );
255 // We force the original context
256 // (plain objects used as context get extended)
257 s.context = options.context;
260 jQuery_lastModified = jQuery.lastModified,
261 jQuery_etag = jQuery.etag,
262 // Callbacks contexts
263 callbackContext = s.context || s,
264 globalEventContext = s.context ? jQuery( s.context ) : jQuery.event,
266 deferred = jQuery.Deferred(),
267 completeDeferred = jQuery._Deferred(),
268 // Headers (they are sent all at once)
271 responseHeadersString,
277 // Cross-domain detection vars
278 loc = document.location,
290 setRequestHeader: function(name,value) {
292 requestHeaders[ name.toLowerCase() ] = value;
298 getAllResponseHeaders: function() {
299 return state === 2 ? responseHeadersString : null;
302 // Builds headers hashtable if needed
303 // (match is used internally)
304 getResponseHeader: function( key , match ) {
310 if ( responseHeaders === undefined ) {
312 responseHeaders = {};
314 if ( typeof responseHeadersString === "string" ) {
316 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
317 responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
321 return responseHeaders[ key.toLowerCase() ];
324 // Cancel the request
325 abort: function( statusText ) {
326 if ( transport && state !== 2 ) {
327 transport.abort( statusText || "abort" );
328 done( 0 , statusText );
334 // Callback for when everything is done
335 // It is defined here because jslint complains if it is declared
336 // at the end of the function (which would be more logical and readable)
337 function done( status , statusText , response , headers) {
344 // State is "done" now
348 jXHR.readyState = status ? 4 : 0;
350 // Cache response headers
351 responseHeadersString = headers || "";
353 // Clear timeout if it exists
354 if ( timeoutTimer ) {
355 clearTimeout(timeoutTimer);
360 // and ifModified status
361 ifModified = s.ifModified,
370 // If successful, handle type chaining
371 if ( status >= 200 && status < 300 || status === 304 ) {
373 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
374 if ( s.ifModified ) {
376 var lastModified = jXHR.getResponseHeader("Last-Modified"),
377 etag = jXHR.getResponseHeader("Etag");
380 jQuery_lastModified[ s.url ] = lastModified;
383 jQuery_etag[ s.url ] = etag;
388 if ( status === 304 ) {
390 // Set the statusText accordingly
391 statusText = "notmodified";
398 // Set the statusText accordingly
399 statusText = "success";
401 // Chain data conversions and determine the final value
402 // (if an exception is thrown in the process, it'll be notified as an error)
410 // Conversion function
412 // Conversion functions (when text is used in-between)
415 // Local references to dataTypes & converters
416 dataTypes = s.dataTypes,
417 converters = s.converters,
418 // DataType to responseXXX field mapping
424 // For each dataType in the chain
425 for( i = 0 ; i < dataTypes.length ; i++ ) {
427 current = dataTypes[ i ];
429 // If a responseXXX field for this dataType exists
430 // and if it hasn't been set yet
431 if ( responses[ current ] ) {
433 jXHR[ "response" + responses[ current ] ] = response;
435 responses[ current ] = 0;
438 // If this is not the first element
441 // Get the dataType to convert from
442 prev = dataTypes[ i - 1 ];
444 // If no catch-all and dataTypes are actually different
445 if ( prev !== "*" && current !== "*" && prev !== current ) {
448 conv = converters[ prev + " " + current ] ||
449 converters[ "* " + current ];
453 // If there is no direct converter and none of the dataTypes is text
454 if ( ! conv && prev !== "text" && current !== "text" ) {
455 // Try with text in-between
456 conv1 = converters[ prev + " text" ] || converters[ "* text" ];
457 conv2 = converters[ "text " + current ];
458 // Revert back to a single converter
459 // if one of the converter is an equivalence
460 if ( conv1 === true ) {
462 } else if ( conv2 === true ) {
466 // If we found no converter, dispatch an error
467 if ( ! ( conv || conv1 && conv2 ) ) {
470 // If found converter is not an equivalence
471 if ( conv !== true ) {
472 // Convert with 1 or 2 converters accordingly
473 response = conv ? conv( response ) : conv2( conv1( response ) );
476 // If it is the first element of the chain
477 // and we have a dataFilter
478 } else if ( s.dataFilter ) {
479 // Apply the dataFilter
480 response = s.dataFilter( response , current );
481 // Get dataTypes again in case the filter changed them
482 dataTypes = s.dataTypes;
487 // We have a real success
491 // If an exception was thrown
494 // We have a parsererror
495 statusText = "parsererror";
501 // if not success, mark it as an error
504 error = statusText = statusText || "error";
506 // Set responseText if needed
508 jXHR.responseText = response;
512 // Set data for the fake xhr object
513 jXHR.status = status;
514 jXHR.statusText = statusText;
518 deferred.fire( callbackContext , [ success , statusText , jXHR ] );
520 deferred.fireReject( callbackContext , [ jXHR , statusText , error ] );
524 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ) ,
525 [ jXHR , s , isSuccess ? success : error ] );
529 completeDeferred.fire( callbackContext, [ jXHR , statusText ] );
532 globalEventContext.trigger( "ajaxComplete" , [ jXHR , s] );
533 // Handle the global AJAX counter
534 if ( ! --jQuery.active ) {
535 jQuery.event.trigger( "ajaxStop" );
541 deferred.promise( jXHR );
542 jXHR.success = jXHR.done;
543 jXHR.error = jXHR.fail;
544 jXHR.complete = completeDeferred.done;
546 // Remove hash character (#7531: and string promotion)
547 s.url = ( "" + s.url ).replace( rhash , "" );
549 // Uppercase the type
550 s.type = s.type.toUpperCase();
552 // Determine if request has content
553 s.hasContent = ! rnoContent.test( s.type );
555 // Extract dataTypes list
556 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( /\s+/ );
558 // Determine if a cross-domain request is in order
559 if ( ! s.crossDomain ) {
560 parts = rurl.exec( s.url.toLowerCase() );
563 ( parts[ 1 ] && parts[ 1 ] != loc.protocol ||
564 parts[ 2 ] != loc.hostname ||
565 ( parts[ 3 ] || 80 ) != ( loc.port || 80 ) )
569 // Convert data if not already a string
570 if ( s.data && s.processData && typeof s.data != "string" ) {
571 s.data = jQuery.param( s.data , s.traditional );
575 transport = jQuery.ajax.prefilter( s , options ).transport( s );
577 // Watch for a new set of requests
578 if ( s.global && jQuery.active++ === 0 ) {
579 jQuery.event.trigger( "ajaxStart" );
582 // If no transport, we auto-abort
585 done( 0 , "transport not found" );
590 // More options handling for requests with no content
591 if ( ! s.hasContent ) {
593 // If data is available, append data to url
595 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
598 // Add anti-cache in url if needed
599 if ( s.cache === false ) {
601 var ts = jQuery.now(),
602 // try replacing _= if it is there
603 ret = s.url.replace( rts , "$1_=" + ts );
605 // if nothing was replaced, add timestamp to the end
606 s.url = ret + ( (ret == s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "");
610 // Set the correct header, if data is being sent
611 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
612 requestHeaders[ "content-type" ] = s.contentType;
615 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
616 if ( s.ifModified ) {
617 if ( jQuery_lastModified[ s.url ] ) {
618 requestHeaders[ "if-modified-since" ] = jQuery_lastModified[ s.url ];
620 if ( jQuery_etag[ s.url ] ) {
621 requestHeaders[ "if-none-match" ] = jQuery_etag[ s.url ];
625 // Set the Accepts header for the server, depending on the dataType
626 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
627 s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
630 // Check for headers option
631 for ( i in s.headers ) {
632 requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
635 // Allow custom headers/mimetypes and early abort
636 if ( s.beforeSend && ( s.beforeSend.call( callbackContext , jXHR , s ) === false || state === 2 ) ) {
638 // Abort if not done already
644 // Set state as sending
648 // Install callbacks on deferreds
649 for ( i in { success:1, error:1, complete:1 } ) {
655 globalEventContext.trigger( "ajaxSend" , [ jXHR , s ] );
659 if ( s.async && s.timeout > 0 ) {
660 timeoutTimer = setTimeout(function(){
661 jXHR.abort( "timeout" );
667 transport.send(requestHeaders, done);
669 // Propagate exception as error if not done
670 if ( status === 1 ) {
672 done(0, "error", "" + e);
675 // Simply rethrow otherwise
686 // Serialize an array of form elements or a set of
687 // key/values into a query string
688 param: function( a, traditional ) {
690 add = function( key, value ) {
691 // If value is a function, invoke it and return its value
692 value = jQuery.isFunction(value) ? value() : value;
693 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
696 // Set traditional to true for jQuery <= 1.3.2 behavior.
697 if ( traditional === undefined ) {
698 traditional = jQuery.ajaxSettings.traditional;
701 // If an array was passed in, assume that it is an array of form elements.
702 if ( jQuery.isArray(a) || a.jquery ) {
703 // Serialize the form elements
704 jQuery.each( a, function() {
705 add( this.name, this.value );
709 // If traditional, encode the "old" way (the way 1.3.2 or older
710 // did it), otherwise encode params recursively.
711 for ( var prefix in a ) {
712 buildParams( prefix, a[prefix], traditional, add );
716 // Return the resulting serialization
717 return s.join("&").replace(r20, "+");
721 function buildParams( prefix, obj, traditional, add ) {
722 if ( jQuery.isArray(obj) && obj.length ) {
723 // Serialize array item.
724 jQuery.each( obj, function( i, v ) {
725 if ( traditional || rbracket.test( prefix ) ) {
726 // Treat each array item as a scalar.
730 // If array item is non-scalar (array or object), encode its
731 // numeric index to resolve deserialization ambiguity issues.
732 // Note that rack (as of 1.0.0) can't currently deserialize
733 // nested arrays properly, and attempting to do so may cause
734 // a server error. Possible fixes are to modify rack's
735 // deserialization algorithm or to provide an option or flag
736 // to force array serialization to be shallow.
737 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
741 } else if ( !traditional && obj != null && typeof obj === "object" ) {
742 // If we see an array here, it is empty and should be treated as an empty
744 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
747 // Serialize object item.
749 jQuery.each( obj, function( k, v ) {
750 buildParams( prefix + "[" + k + "]", v, traditional, add );
755 // Serialize scalar item.
760 // This is still on the jQuery object... for now
761 // Want to move this to jQuery.ajax some day
764 // Counter for holding the number of active queries
767 // Last-Modified header cache for next request
773 //Execute or select from functions in a given structure of options
774 function ajax_selectOrExecute( structure , s ) {
776 var dataTypes = s.dataTypes,
784 noSelect = structure !== "transports";
786 function initSearch( dataType ) {
788 flag = transportDataType !== dataType && ! checked[ dataType ];
792 checked[ dataType ] = 1;
793 transportDataType = dataType;
794 list = s[ structure ][ dataType ];
796 length = list ? list.length : 0 ;
802 initSearch( dataTypes[ 0 ] );
804 for ( i = 0 ; ( noSelect || ! selected ) && i <= length ; i++ ) {
806 if ( i === length ) {
812 selected = list[ i ]( s , determineDataType );
814 // If we got redirected to another dataType
815 // Search there (if not in progress or already tried)
816 if ( typeof( selected ) === "string" &&
817 initSearch( selected ) ) {
819 dataTypes.unshift( selected );
825 return noSelect ? jQuery.ajax : selected;
828 // Add an element to one of the structures in ajaxSettings
829 function ajax_addElement( structure , args ) {
833 length = args.length,
844 first = jQuery.type( args[ 0 ] );
846 if ( first === "object" ) {
847 return ajax_selectOrExecute( structure , args[ 0 ] );
850 structure = jQuery.ajaxSettings[ structure ];
852 if ( first !== "function" ) {
854 dataTypes = args[ 0 ].toLowerCase().split(/\s+/);
855 dLength = dataTypes.length;
860 if ( dLength && start < length ) {
862 functors = sliceFunc.call( args , start );
864 for( i = 0 ; i < dLength ; i++ ) {
866 dataType = dataTypes[ i ];
868 first = /^\+/.test( dataType );
871 dataType = dataType.substr(1);
874 if ( dataType !== "" ) {
876 append = Array.prototype[ first ? "unshift" : "push" ];
877 list = structure[ dataType ] = structure[ dataType ] || [];
878 append.apply( list , functors );
887 // Install prefilter & transport methods
888 jQuery.each( [ "prefilter" , "transport" ] , function( _ , name ) {
890 jQuery.ajax[ name ] = function() {
891 return ajax_addElement( _ , arguments );
895 // Utility function that handles dataType when response is received
896 // (for those transports that can give text or xml responses)
897 function determineDataType( s , ct , text , xml ) {
899 var contents = s.contents,
902 dataTypes = s.dataTypes,
903 transportDataType = dataTypes[0],
906 // Auto (xml, json, script or text determined given headers)
907 if ( transportDataType === "*" ) {
909 for ( type in contents ) {
910 if ( ( regexp = contents[ type ] ) && regexp.test( ct ) ) {
911 transportDataType = dataTypes[0] = type;
917 // xml and parsed as such
918 if ( transportDataType === "xml" &&
920 xml.documentElement /* #4958 */ ) {
924 // Text response was provided
929 // If it's not really text, defer to converters
930 if ( transportDataType !== "text" ) {
931 dataTypes.unshift( "text" );
940 * Create the request object; Microsoft failed to properly
941 * implement the XMLHttpRequest in IE7 (can't request local files),
942 * so we use the ActiveXObject when it is available
943 * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
944 * we need a fallback.
946 if ( window.ActiveXObject ) {
947 jQuery.ajaxSettings.xhr = function() {
948 if ( window.location.protocol !== "file:" ) {
950 return new window.XMLHttpRequest();
951 } catch( xhrError ) {}
955 return new window.ActiveXObject("Microsoft.XMLHTTP");
956 } catch( activeError ) {}
960 var testXHR = jQuery.ajaxSettings.xhr();
962 // Does this browser support XHR requests?
963 jQuery.support.ajax = !!testXHR;
965 // Does this browser support crossDomain XHR requests
966 jQuery.support.cors = testXHR && "withCredentials" in testXHR;