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",
185 return new window.XMLHttpRequest();
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
238 // (s is used internally)
239 ajax: function( url , options , s ) {
242 if ( arguments.length === 1 ) {
244 url = options ? options.url : undefined;
247 // Force options to be an object
248 options = options || {};
250 // Get the url if provided separately
251 options.url = url || options.url;
253 // Create the final options object
254 s = jQuery.extend( true , {} , jQuery.ajaxSettings , options );
256 // We force the original context
257 // (plain objects used as context get extended)
258 s.context = options.context;
261 jQuery_lastModified = jQuery.lastModified,
262 jQuery_etag = jQuery.etag,
263 // Callbacks contexts
264 callbackContext = s.context || s,
265 globalEventContext = s.context ? jQuery( s.context ) : jQuery.event,
267 deferred = jQuery.Deferred(),
268 completeDeferred = jQuery._Deferred(),
269 // Status-dependent callbacks
270 statusCode = s.statusCode || {},
271 // Headers (they are sent all at once)
274 responseHeadersString,
280 // Cross-domain detection vars
281 loc = document.location,
293 setRequestHeader: function(name,value) {
295 requestHeaders[ name.toLowerCase() ] = value;
301 getAllResponseHeaders: function() {
302 return state === 2 ? responseHeadersString : null;
305 // Builds headers hashtable if needed
306 // (match is used internally)
307 getResponseHeader: function( key , match ) {
311 if ( responseHeaders === undefined ) {
313 responseHeaders = {};
315 if ( typeof responseHeadersString === "string" ) {
317 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
318 responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
322 match = responseHeaders[ key.toLowerCase() ];
332 // Cancel the request
333 abort: function( statusText ) {
335 transport.abort( statusText || "abort" );
337 done( 0 , statusText );
342 // Callback for when everything is done
343 // It is defined here because jslint complains if it is declared
344 // at the end of the function (which would be more logical and readable)
345 function done( status , statusText , response , headers) {
352 // State is "done" now
355 // Dereference transport for early garbage collection
356 // (no matter how long the jXHR transport will be used
360 jXHR.readyState = status ? 4 : 0;
362 // Cache response headers
363 responseHeadersString = headers || "";
365 // Clear timeout if it exists
366 if ( timeoutTimer ) {
367 clearTimeout(timeoutTimer);
372 // and ifModified status
373 ifModified = s.ifModified,
382 // If successful, handle type chaining
383 if ( status >= 200 && status < 300 || status === 304 ) {
385 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
386 if ( s.ifModified ) {
388 var lastModified = jXHR.getResponseHeader("Last-Modified"),
389 etag = jXHR.getResponseHeader("Etag");
392 jQuery_lastModified[ s.url ] = lastModified;
395 jQuery_etag[ s.url ] = etag;
400 if ( status === 304 ) {
402 // Set the statusText accordingly
403 statusText = "notmodified";
410 // Set the statusText accordingly
411 statusText = "success";
413 // Chain data conversions and determine the final value
414 // (if an exception is thrown in the process, it'll be notified as an error)
422 // Conversion function
424 // Conversion functions (when text is used in-between)
427 // Local references to dataTypes & converters
428 dataTypes = s.dataTypes,
429 converters = s.converters,
430 // DataType to responseXXX field mapping
436 // For each dataType in the chain
437 for( i = 0 ; i < dataTypes.length ; i++ ) {
439 current = dataTypes[ i ];
441 // If a responseXXX field for this dataType exists
442 // and if it hasn't been set yet
443 if ( responses[ current ] ) {
445 jXHR[ "response" + responses[ current ] ] = response;
447 responses[ current ] = 0;
450 // If this is not the first element
453 // Get the dataType to convert from
454 prev = dataTypes[ i - 1 ];
456 // If no catch-all and dataTypes are actually different
457 if ( prev !== "*" && current !== "*" && prev !== current ) {
460 conv = converters[ prev + " " + current ] ||
461 converters[ "* " + current ];
465 // If there is no direct converter and none of the dataTypes is text
466 if ( ! conv && prev !== "text" && current !== "text" ) {
467 // Try with text in-between
468 conv1 = converters[ prev + " text" ] || converters[ "* text" ];
469 conv2 = converters[ "text " + current ];
470 // Revert back to a single converter
471 // if one of the converter is an equivalence
472 if ( conv1 === true ) {
474 } else if ( conv2 === true ) {
478 // If we found no converter, dispatch an error
479 if ( ! ( conv || conv1 && conv2 ) ) {
482 // If found converter is not an equivalence
483 if ( conv !== true ) {
484 // Convert with 1 or 2 converters accordingly
485 response = conv ? conv( response ) : conv2( conv1( response ) );
488 // If it is the first element of the chain
489 // and we have a dataFilter
490 } else if ( s.dataFilter ) {
491 // Apply the dataFilter
492 response = s.dataFilter( response , current );
493 // Get dataTypes again in case the filter changed them
494 dataTypes = s.dataTypes;
499 // We have a real success
503 // If an exception was thrown
506 // We have a parsererror
507 statusText = "parsererror";
513 // if not success, mark it as an error
516 error = statusText = statusText || "error";
518 // Set responseText if needed
520 jXHR.responseText = response;
524 // Set data for the fake xhr object
525 jXHR.status = status;
526 jXHR.statusText = statusText;
530 deferred.fire( callbackContext , [ success , statusText , jXHR ] );
532 deferred.fireReject( callbackContext , [ jXHR , statusText , error ] );
535 // Status-dependent callbacks
536 jXHR.statusCode( statusCode );
539 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ) ,
540 [ jXHR , s , isSuccess ? success : error ] );
544 completeDeferred.fire( callbackContext, [ jXHR , statusText ] );
547 globalEventContext.trigger( "ajaxComplete" , [ jXHR , s] );
548 // Handle the global AJAX counter
549 if ( ! --jQuery.active ) {
550 jQuery.event.trigger( "ajaxStop" );
556 deferred.promise( jXHR );
557 jXHR.success = jXHR.done;
558 jXHR.error = jXHR.fail;
559 jXHR.complete = completeDeferred.done;
561 // Status-dependent callbacks
562 jXHR.statusCode = function( map ) {
564 var resolved = jXHR.isResolved(),
566 if ( resolved || jXHR.isRejected() ) {
567 tmp = map[ jXHR.status ];
569 if ( map === statusCode ) {
570 delete statusCode[ jXHR.status ];
572 jXHR[ resolved ? "done" : "fail" ]( tmp );
576 statusCode[ tmp ] = [ statusCode[ tmp ] , map[ tmp ] ];
583 // Remove hash character (#7531: and string promotion)
584 s.url = ( "" + s.url ).replace( rhash , "" );
586 // Uppercase the type
587 s.type = s.type.toUpperCase();
589 // Determine if request has content
590 s.hasContent = ! rnoContent.test( s.type );
592 // Extract dataTypes list
593 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( /\s+/ );
595 // Determine if a cross-domain request is in order
596 if ( ! s.crossDomain ) {
597 parts = rurl.exec( s.url.toLowerCase() );
600 ( parts[ 1 ] && parts[ 1 ] != loc.protocol ||
601 parts[ 2 ] != loc.hostname ||
602 ( parts[ 3 ] || 80 ) != ( loc.port || 80 ) )
606 // Convert data if not already a string
607 if ( s.data && s.processData && typeof s.data != "string" ) {
608 s.data = jQuery.param( s.data , s.traditional );
612 jQuery.ajaxPrefilter( s , options );
614 // Watch for a new set of requests
615 if ( s.global && jQuery.active++ === 0 ) {
616 jQuery.event.trigger( "ajaxStart" );
619 // More options handling for requests with no content
620 if ( ! s.hasContent ) {
622 // If data is available, append data to url
624 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
627 // Add anti-cache in url if needed
628 if ( s.cache === false ) {
630 var ts = jQuery.now(),
631 // try replacing _= if it is there
632 ret = s.url.replace( rts , "$1_=" + ts );
634 // if nothing was replaced, add timestamp to the end
635 s.url = ret + ( (ret == s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "");
639 // Set the correct header, if data is being sent
640 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
641 requestHeaders[ "content-type" ] = s.contentType;
644 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
645 if ( s.ifModified ) {
646 if ( jQuery_lastModified[ s.url ] ) {
647 requestHeaders[ "if-modified-since" ] = jQuery_lastModified[ s.url ];
649 if ( jQuery_etag[ s.url ] ) {
650 requestHeaders[ "if-none-match" ] = jQuery_etag[ s.url ];
654 // Set the Accepts header for the server, depending on the dataType
655 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
656 s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
659 // Check for headers option
660 for ( i in s.headers ) {
661 requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
664 // Allow custom headers/mimetypes and early abort
665 if ( s.beforeSend && ( s.beforeSend.call( callbackContext , jXHR , s ) === false || state === 2 ) ) {
667 // Abort if not done already
675 // Install callbacks on deferreds
676 for ( i in { success:1, error:1, complete:1 } ) {
681 transport = jQuery.ajaxTransport( s );
683 // If no transport, we auto-abort
686 done( 0 , "notransport" );
690 // Set state as sending
691 state = jXHR.readyState = 1;
695 globalEventContext.trigger( "ajaxSend" , [ jXHR , s ] );
699 if ( s.async && s.timeout > 0 ) {
700 timeoutTimer = setTimeout(function(){
701 jXHR.abort( "timeout" );
707 transport.send(requestHeaders, done);
709 // Propagate exception as error if not done
710 if ( status === 1 ) {
712 done(0, "error", "" + e);
715 // Simply rethrow otherwise
726 // Serialize an array of form elements or a set of
727 // key/values into a query string
728 param: function( a, traditional ) {
730 add = function( key, value ) {
731 // If value is a function, invoke it and return its value
732 value = jQuery.isFunction(value) ? value() : value;
733 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
736 // Set traditional to true for jQuery <= 1.3.2 behavior.
737 if ( traditional === undefined ) {
738 traditional = jQuery.ajaxSettings.traditional;
741 // If an array was passed in, assume that it is an array of form elements.
742 if ( jQuery.isArray(a) || a.jquery ) {
743 // Serialize the form elements
744 jQuery.each( a, function() {
745 add( this.name, this.value );
749 // If traditional, encode the "old" way (the way 1.3.2 or older
750 // did it), otherwise encode params recursively.
751 for ( var prefix in a ) {
752 buildParams( prefix, a[prefix], traditional, add );
756 // Return the resulting serialization
757 return s.join("&").replace(r20, "+");
761 function buildParams( prefix, obj, traditional, add ) {
762 if ( jQuery.isArray(obj) && obj.length ) {
763 // Serialize array item.
764 jQuery.each( obj, function( i, v ) {
765 if ( traditional || rbracket.test( prefix ) ) {
766 // Treat each array item as a scalar.
770 // If array item is non-scalar (array or object), encode its
771 // numeric index to resolve deserialization ambiguity issues.
772 // Note that rack (as of 1.0.0) can't currently deserialize
773 // nested arrays properly, and attempting to do so may cause
774 // a server error. Possible fixes are to modify rack's
775 // deserialization algorithm or to provide an option or flag
776 // to force array serialization to be shallow.
777 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
781 } else if ( !traditional && obj != null && typeof obj === "object" ) {
782 // If we see an array here, it is empty and should be treated as an empty
784 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
787 // Serialize object item.
789 jQuery.each( obj, function( k, v ) {
790 buildParams( prefix + "[" + k + "]", v, traditional, add );
795 // Serialize scalar item.
800 // This is still on the jQuery object... for now
801 // Want to move this to jQuery.ajax some day
804 // Counter for holding the number of active queries
807 // Last-Modified header cache for next request
813 //Execute or select from functions in a given structure of options
814 function ajax_selectOrExecute( structure , s ) {
816 var dataTypes = s.dataTypes,
824 noSelect = structure !== "transports";
826 function initSearch( dataType ) {
828 flag = transportDataType !== dataType && ! checked[ dataType ];
832 checked[ dataType ] = 1;
833 transportDataType = dataType;
834 list = s[ structure ][ dataType ];
836 length = list ? list.length : 0 ;
842 initSearch( dataTypes[ 0 ] );
844 for ( i = 0 ; ( noSelect || ! selected ) && i <= length ; i++ ) {
846 if ( i === length ) {
852 selected = list[ i ]( s , determineDataType );
854 // If we got redirected to another dataType
855 // Search there (if not in progress or already tried)
856 if ( typeof( selected ) === "string" &&
857 initSearch( selected ) ) {
859 dataTypes.unshift( selected );
865 return noSelect ? jQuery : selected;
868 // Add an element to one of the structures in ajaxSettings
869 function ajax_addElement( structure , args ) {
873 length = args.length,
884 first = jQuery.type( args[ 0 ] );
886 if ( first === "object" ) {
887 return ajax_selectOrExecute( structure , args[ 0 ] );
890 structure = jQuery.ajaxSettings[ structure ];
892 if ( first !== "function" ) {
894 dataTypes = args[ 0 ].toLowerCase().split(/\s+/);
895 dLength = dataTypes.length;
900 if ( dLength && start < length ) {
902 functors = sliceFunc.call( args , start );
904 for( i = 0 ; i < dLength ; i++ ) {
906 dataType = dataTypes[ i ];
908 first = /^\+/.test( dataType );
911 dataType = dataType.substr(1);
914 if ( dataType !== "" ) {
916 append = Array.prototype[ first ? "unshift" : "push" ];
917 list = structure[ dataType ] = structure[ dataType ] || [];
918 append.apply( list , functors );
927 // Install prefilter & transport methods
928 jQuery.each( [ "Prefilter" , "Transport" ] , function( _ , name ) {
929 _ = name.toLowerCase() + "s";
930 jQuery[ "ajax" + name ] = function() {
931 return ajax_addElement( _ , arguments );
935 // Utility function that handles dataType when response is received
936 // (for those transports that can give text or xml responses)
937 function determineDataType( s , ct , text , xml ) {
939 var contents = s.contents,
942 dataTypes = s.dataTypes,
943 transportDataType = dataTypes[0],
946 // Auto (xml, json, script or text determined given headers)
947 if ( transportDataType === "*" ) {
949 for ( type in contents ) {
950 if ( ( regexp = contents[ type ] ) && regexp.test( ct ) ) {
951 transportDataType = dataTypes[0] = type;
957 // xml and parsed as such
958 if ( transportDataType === "xml" &&
960 xml.documentElement /* #4958 */ ) {
964 // Text response was provided
969 // If it's not really text, defer to converters
970 if ( transportDataType !== "text" ) {
971 dataTypes.unshift( "text" );
980 * Create the request object; Microsoft failed to properly
981 * implement the XMLHttpRequest in IE7 (can't request local files),
982 * so we use the ActiveXObject when it is available
983 * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
984 * we need a fallback.
986 if ( window.ActiveXObject ) {
987 jQuery.ajaxSettings.xhr = function() {
988 if ( window.location.protocol !== "file:" ) {
990 return new window.XMLHttpRequest();
991 } catch( xhrError ) {}
995 return new window.ActiveXObject("Microsoft.XMLHTTP");
996 } catch( activeError ) {}
1000 var testXHR = jQuery.ajaxSettings.xhr();
1002 // Does this browser support XHR requests?
1003 jQuery.support.ajax = !!testXHR;
1005 // Does this browser support crossDomain XHR requests
1006 jQuery.support.cors = testXHR && "withCredentials" in testXHR;