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( 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,
287 setRequestHeader: function(name,value) {
289 requestHeaders[ name.toLowerCase() ] = value;
295 getAllResponseHeaders: function() {
296 return state === 2 ? responseHeadersString : null;
299 // Builds headers hashtable if needed
300 // (match is used internally)
301 getResponseHeader: function( key , match ) {
307 if ( responseHeaders === undefined ) {
309 responseHeaders = {};
311 if ( typeof responseHeadersString === "string" ) {
313 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
314 responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
318 return responseHeaders[ key.toLowerCase() ];
321 // Cancel the request
322 abort: function( statusText ) {
323 if ( transport && state !== 2 ) {
324 transport.abort( statusText || "abort" );
325 done( 0 , statusText );
331 // Callback for when everything is done
332 // It is defined here because jslint complains if it is declared
333 // at the end of the function (which would be more logical and readable)
334 function done( status , statusText , response , headers) {
341 // State is "done" now
345 jXHR.readyState = status ? 4 : 0;
347 // Cache response headers
348 responseHeadersString = headers || "";
350 // Clear timeout if it exists
351 if ( timeoutTimer ) {
352 clearTimeout(timeoutTimer);
357 // and ifModified status
358 ifModified = s.ifModified,
367 // If not timeout, force a jQuery-compliant status text
368 if ( statusText != "timeout" ) {
369 statusText = ( status >= 200 && status < 300 ) ?
371 ( status === 304 ? "notmodified" : "error" );
374 // If successful, handle type chaining
375 if ( statusText === "success" || statusText === "notmodified" ) {
377 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
378 if ( s.ifModified ) {
380 var lastModified = jXHR.getResponseHeader("Last-Modified"),
381 etag = jXHR.getResponseHeader("Etag");
384 jQuery_lastModified[ s.url ] = lastModified;
387 jQuery_etag[ s.url ] = etag;
391 if ( s.ifModified && statusText === "notmodified" ) {
397 // Chain data conversions and determine the final value
398 // (if an exception is thrown in the process, it'll be notified as an error)
409 dataTypes = s.dataTypes,
410 converters = s.converters,
416 for( i = 0 ; i < dataTypes.length ; i++ ) {
418 current = dataTypes[ i ];
420 if ( responses[ current ] ) {
421 jXHR[ "response" + responses[ current ] ] = response;
422 responses[ current ] = 0;
427 prev = dataTypes[ i - 1 ];
429 if ( prev !== "*" && current !== "*" && prev !== current ) {
431 conv = converters[ ( conversion = prev + " " + current ) ] ||
432 converters[ "* " + current ];
436 if ( ! conv && prev !== "text" && current !== "text" ) {
437 conv1 = converters[ prev + " text" ] || converters[ "* text" ];
438 conv2 = converters[ "text " + current ];
439 if ( conv1 === true ) {
441 } else if ( conv2 === true ) {
446 if ( ! ( conv || conv1 && conv2 ) ) {
450 if ( conv !== true ) {
451 response = conv ? conv( response ) : conv2( conv1( response ) );
454 } else if ( s.dataFilter ) {
456 response = s.dataFilter( response );
457 dataTypes = s.dataTypes;
461 // We have a real success
467 statusText = "parsererror";
473 } else { // if not success, mark it as an error
475 error = error || statusText;
477 // Set responseText if needed
479 jXHR.responseText = response;
483 // Set data for the fake xhr object
484 jXHR.status = status;
485 jXHR.statusText = statusText;
489 deferred.fire( callbackContext , [ success , statusText , jXHR ] );
491 deferred.fireReject( callbackContext , [ jXHR , statusText , error ] );
495 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ) ,
496 [ jXHR , s , isSuccess ? success : error ] );
500 completeDeferred.fire( callbackContext, [ jXHR , statusText ] );
503 globalEventContext.trigger( "ajaxComplete" , [ jXHR , s] );
504 // Handle the global AJAX counter
505 if ( ! --jQuery.active ) {
506 jQuery.event.trigger( "ajaxStop" );
512 deferred.promise( jXHR );
513 jXHR.success = jXHR.done;
514 jXHR.error = jXHR.fail;
515 jXHR.complete = completeDeferred.done;
517 // Remove hash character (#7531: and string promotion)
518 s.url = ( "" + s.url ).replace( rhash , "" );
520 // Uppercase the type
521 s.type = s.type.toUpperCase();
523 // Determine if request has content
524 s.hasContent = ! rnoContent.test( s.type );
526 // Extract dataTypes list
527 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( /\s+/ );
529 // Determine if a cross-domain request is in order
530 var parts = rurl.exec( s.url.toLowerCase() ),
533 if ( ! s.crossDomain ) {
536 ( parts[ 1 ] && parts[ 1 ] != loc.protocol ||
537 parts[ 2 ] != loc.hostname ||
538 ( parts[ 3 ] || 80 ) != ( loc.port || 80 ) )
542 // Convert data if not already a string
543 if ( s.data && s.processData && typeof s.data != "string" ) {
544 s.data = jQuery.param( s.data , s.traditional );
548 transport = jQuery.ajax.prefilter( s , options ).transport( s );
550 // Watch for a new set of requests
551 if ( s.global && jQuery.active++ === 0 ) {
552 jQuery.event.trigger( "ajaxStart" );
555 // If no transport, we auto-abort
558 done( 0 , "transport not found" );
563 // More options handling for requests with no content
564 if ( ! s.hasContent ) {
566 // If data is available, append data to url
568 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
571 // Add anti-cache in url if needed
572 if ( s.cache === false ) {
574 var ts = jQuery.now(),
575 // try replacing _= if it is there
576 ret = s.url.replace( rts , "$1_=" + ts );
578 // if nothing was replaced, add timestamp to the end
579 s.url = ret + ( (ret == s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "");
583 // Set the correct header, if data is being sent
584 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
585 requestHeaders[ "content-type" ] = s.contentType;
588 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
589 if ( s.ifModified ) {
590 if ( jQuery_lastModified[ s.url ] ) {
591 requestHeaders[ "if-modified-since" ] = jQuery_lastModified[ s.url ];
593 if ( jQuery_etag[ s.url ] ) {
594 requestHeaders[ "if-none-match" ] = jQuery_etag[ s.url ];
598 // Set the Accepts header for the server, depending on the dataType
599 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
600 s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
603 // Check for headers option
604 for ( i in s.headers ) {
605 requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
608 // Allow custom headers/mimetypes and early abort
609 if ( s.beforeSend && ( s.beforeSend.call( callbackContext , jXHR , s ) === false || state === 2 ) ) {
611 // Abort if not done already
617 // Set state as sending
621 // Install callbacks on deferreds
622 for ( i in { success:1, error:1, complete:1 } ) {
628 globalEventContext.trigger( "ajaxSend" , [ jXHR , s ] );
632 if ( s.async && s.timeout > 0 ) {
633 timeoutTimer = setTimeout(function(){
634 jXHR.abort( "timeout" );
640 transport.send(requestHeaders, done);
642 // Propagate exception as error if not done
643 if ( status === 1 ) {
645 done(0, "error", "" + e);
648 // Simply rethrow otherwise
659 // Serialize an array of form elements or a set of
660 // key/values into a query string
661 param: function( a, traditional ) {
663 add = function( key, value ) {
664 // If value is a function, invoke it and return its value
665 value = jQuery.isFunction(value) ? value() : value;
666 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
669 // Set traditional to true for jQuery <= 1.3.2 behavior.
670 if ( traditional === undefined ) {
671 traditional = jQuery.ajaxSettings.traditional;
674 // If an array was passed in, assume that it is an array of form elements.
675 if ( jQuery.isArray(a) || a.jquery ) {
676 // Serialize the form elements
677 jQuery.each( a, function() {
678 add( this.name, this.value );
682 // If traditional, encode the "old" way (the way 1.3.2 or older
683 // did it), otherwise encode params recursively.
684 for ( var prefix in a ) {
685 buildParams( prefix, a[prefix], traditional, add );
689 // Return the resulting serialization
690 return s.join("&").replace(r20, "+");
694 function buildParams( prefix, obj, traditional, add ) {
695 if ( jQuery.isArray(obj) && obj.length ) {
696 // Serialize array item.
697 jQuery.each( obj, function( i, v ) {
698 if ( traditional || rbracket.test( prefix ) ) {
699 // Treat each array item as a scalar.
703 // If array item is non-scalar (array or object), encode its
704 // numeric index to resolve deserialization ambiguity issues.
705 // Note that rack (as of 1.0.0) can't currently deserialize
706 // nested arrays properly, and attempting to do so may cause
707 // a server error. Possible fixes are to modify rack's
708 // deserialization algorithm or to provide an option or flag
709 // to force array serialization to be shallow.
710 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
714 } else if ( !traditional && obj != null && typeof obj === "object" ) {
715 // If we see an array here, it is empty and should be treated as an empty
717 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
720 // Serialize object item.
722 jQuery.each( obj, function( k, v ) {
723 buildParams( prefix + "[" + k + "]", v, traditional, add );
728 // Serialize scalar item.
733 // This is still on the jQuery object... for now
734 // Want to move this to jQuery.ajax some day
737 // Counter for holding the number of active queries
740 // Last-Modified header cache for next request
746 //Execute or select from functions in a given structure of options
747 function ajax_selectOrExecute( structure , s ) {
749 var dataTypes = s.dataTypes,
757 noSelect = structure !== "transports";
759 function initSearch( dataType ) {
761 flag = transportDataType !== dataType && ! checked[ dataType ];
765 checked[ dataType ] = 1;
766 transportDataType = dataType;
767 list = s[ structure ][ dataType ];
769 length = list ? list.length : 0 ;
775 initSearch( dataTypes[ 0 ] );
777 for ( i = 0 ; ( noSelect || ! selected ) && i <= length ; i++ ) {
779 if ( i === length ) {
785 selected = list[ i ]( s , determineDataType );
787 // If we got redirected to another dataType
788 // Search there (if not in progress or already tried)
789 if ( typeof( selected ) === "string" &&
790 initSearch( selected ) ) {
792 dataTypes.unshift( selected );
798 return noSelect ? jQuery.ajax : selected;
801 // Add an element to one of the structures in ajaxSettings
802 function ajax_addElement( structure , args ) {
806 length = args.length,
817 first = jQuery.type( args[ 0 ] );
819 if ( first === "object" ) {
820 return ajax_selectOrExecute( structure , args[ 0 ] );
823 structure = jQuery.ajaxSettings[ structure ];
825 if ( first !== "function" ) {
827 dataTypes = args[ 0 ].toLowerCase().split(/\s+/);
828 dLength = dataTypes.length;
833 if ( dLength && start < length ) {
835 functors = sliceFunc.call( args , start );
837 for( i = 0 ; i < dLength ; i++ ) {
839 dataType = dataTypes[ i ];
841 first = /^\+/.test( dataType );
844 dataType = dataType.substr(1);
847 if ( dataType !== "" ) {
849 append = Array.prototype[ first ? "unshift" : "push" ];
850 list = structure[ dataType ] = structure[ dataType ] || [];
851 append.apply( list , functors );
860 // Install prefilter & transport methods
861 jQuery.each( [ "prefilter" , "transport" ] , function( _ , name ) {
863 jQuery.ajax[ name ] = function() {
864 return ajax_addElement( _ , arguments );
868 // Utility function that handles dataType when response is received
869 // (for those transports that can give text or xml responses)
870 function determineDataType( s , ct , text , xml ) {
872 var contents = s.contents,
875 dataTypes = s.dataTypes,
876 transportDataType = dataTypes[0],
879 // Auto (xml, json, script or text determined given headers)
880 if ( transportDataType === "*" ) {
882 for ( type in contents ) {
883 if ( ( regexp = contents[ type ] ) && regexp.test( ct ) ) {
884 transportDataType = dataTypes[0] = type;
890 // xml and parsed as such
891 if ( transportDataType === "xml" &&
893 xml.documentElement /* #4958 */ ) {
897 // Text response was provided
902 // If it's not really text, defer to converters
903 if ( transportDataType !== "text" ) {
904 dataTypes.unshift( "text" );
913 * Create the request object; Microsoft failed to properly
914 * implement the XMLHttpRequest in IE7 (can't request local files),
915 * so we use the ActiveXObject when it is available
916 * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
917 * we need a fallback.
919 if ( window.ActiveXObject ) {
920 jQuery.ajaxSettings.xhr = function() {
921 if ( window.location.protocol !== "file:" ) {
923 return new window.XMLHttpRequest();
924 } catch( xhrError ) {}
928 return new window.ActiveXObject("Microsoft.XMLHTTP");
929 } catch( activeError ) {}
933 var testXHR = jQuery.ajaxSettings.xhr();
935 // Does this browser support XHR requests?
936 jQuery.support.ajax = !!testXHR;
938 // Does this browser support crossDomain XHR requests
939 jQuery.support.cors = testXHR && "withCredentials" in testXHR;