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+))?/,
16 sliceFunc = Array.prototype.slice,
18 // Keep a copy of the old load method
19 _load = jQuery.fn.load;
22 load: function( url, params, callback ) {
23 if ( typeof url !== "string" && _load ) {
24 return _load.apply( this, arguments );
26 // Don't do a request if no elements are being requested
27 } else if ( !this.length ) {
31 var off = url.indexOf(" ");
33 var selector = url.slice(off, url.length);
34 url = url.slice(0, off);
37 // Default to a GET request
40 // If the second parameter was provided
43 if ( jQuery.isFunction( params ) ) {
44 // We assume that it's the callback
48 // Otherwise, build a param string
49 } else if ( typeof params === "object" ) {
50 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
57 // Request the remote document
63 complete: function( res, status ) {
64 // If successful, inject the HTML into all the matched elements
65 if ( status === "success" || status === "notmodified" ) {
66 // See if a selector was specified
68 // Create a dummy div to hold the results
70 // inject the contents of the document in, removing the scripts
71 // to avoid any 'Permission Denied' errors in IE
72 .append(res.responseText.replace(rscript, ""))
74 // Locate the specified elements
77 // If not, just inject the full result
82 self.each( callback, [res.responseText, status, res] );
90 serialize: function() {
91 return jQuery.param(this.serializeArray());
94 serializeArray: function() {
95 return this.map(function(){
96 return this.elements ? jQuery.makeArray(this.elements) : this;
99 return this.name && !this.disabled &&
100 (this.checked || rselectTextarea.test(this.nodeName) ||
101 rinput.test(this.type));
103 .map(function(i, elem){
104 var val = jQuery(this).val();
108 jQuery.isArray(val) ?
109 jQuery.map( val, function(val, i){
110 return {name: elem.name, value: val.replace(/\r?\n/g, "\r\n")};
112 {name: elem.name, value: val.replace(/\r?\n/g, "\r\n")};
117 // Attach a bunch of functions for handling common AJAX events
118 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function(i,o){
119 jQuery.fn[o] = function(f){
120 return this.bind(o, f);
124 jQuery.each( [ "get", "post" ], function( i, method ) {
125 jQuery[ method ] = function( url, data, callback, type ) {
126 // shift arguments if data argument was omited
127 if ( jQuery.isFunction( data ) ) {
128 type = type || callback;
145 getScript: function( url, callback ) {
146 return jQuery.get(url, null, callback, "script");
149 getJSON: function( url, data, callback ) {
150 return jQuery.get(url, data, callback, "json");
153 ajaxSetup: function( settings ) {
154 jQuery.extend( jQuery.ajaxSettings, settings );
161 contentType: "application/x-www-form-urlencoded",
175 return new window.XMLHttpRequest();
179 xml: "application/xml, text/xml",
182 json: "application/json, text/javascript",
193 // 1) They are useful to introduce custom dataTypes (see transport/jsonp for an example)
194 // 2) These are called:
195 // * BEFORE asking for a transport
196 // * AFTER param serialization (s.data is a string if s.processData is true)
197 // 3) key is the dataType
198 // 4) the catchall symbol "*" can be used
199 // 5) execution will start with transport dataType and THEN continue down to "*" if needed
202 // Transports bindings
203 // 1) key is the dataType
204 // 2) the catchall symbol "*" can be used
205 // 3) selection will start with transport dataType and THEN go to "*" if needed
208 // List of data converters
209 // 1) key format is "source_type destination_type" (a single space in-between)
210 // 2) the catchall symbol "*" can be used for source_type
213 // Convert anything to text
214 "* text": window.String,
216 // Text to html (true = no transformation)
219 // Evaluate text as a json expression
220 "text json": jQuery.parseJSON,
223 "text xml": jQuery.parseXML
228 // (s is used internally)
229 ajax: function( url , options , s ) {
232 if ( arguments.length === 1 ) {
234 url = options ? options.url : undefined;
237 // Force options to be an object
238 options = options || {};
240 // Get the url if provided separately
241 options.url = url || options.url;
243 // Create the final options object
244 s = jQuery.extend( true , {} , jQuery.ajaxSettings , options );
246 // We force the original context
247 // (plain objects used as context get extended)
248 s.context = options.context;
251 jQuery_lastModified = jQuery.lastModified,
252 jQuery_etag = jQuery.etag,
253 // Callbacks contexts
254 callbackContext = s.context || s,
255 globalEventContext = s.context ? jQuery( s.context ) : jQuery.event,
257 deferred = jQuery.Deferred(),
258 completeDeferred = jQuery._Deferred(),
259 // Headers (they are sent all at once)
262 responseHeadersString,
278 setRequestHeader: function(name,value) {
280 requestHeaders[ name.toLowerCase() ] = value;
286 getAllResponseHeaders: function() {
287 return state === 2 ? responseHeadersString : null;
290 // Builds headers hashtable if needed
291 // (match is used internally)
292 getResponseHeader: function( key , match ) {
298 if ( responseHeaders === undefined ) {
300 responseHeaders = {};
302 if ( typeof responseHeadersString === "string" ) {
304 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
305 responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
309 return responseHeaders[ key.toLowerCase() ];
312 // Cancel the request
313 abort: function( statusText ) {
314 if ( transport && state !== 2 ) {
315 transport.abort( statusText || "abort" );
316 done( 0 , statusText );
322 // Callback for when everything is done
323 // It is defined here because jslint complains if it is declared
324 // at the end of the function (which would be more logical and readable)
325 function done( status , statusText , response , headers) {
332 // State is "done" now
336 jXHR.readyState = status ? 4 : 0;
338 // Cache response headers
339 responseHeadersString = headers || "";
341 // Clear timeout if it exists
342 if ( timeoutTimer ) {
343 clearTimeout(timeoutTimer);
348 // and ifModified status
349 ifModified = s.ifModified,
358 // If not timeout, force a jQuery-compliant status text
359 if ( statusText != "timeout" ) {
360 statusText = ( status >= 200 && status < 300 ) ?
362 ( status === 304 ? "notmodified" : "error" );
365 // If successful, handle type chaining
366 if ( statusText === "success" || statusText === "notmodified" ) {
368 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
369 if ( s.ifModified ) {
371 var lastModified = jXHR.getResponseHeader("Last-Modified"),
372 etag = jXHR.getResponseHeader("Etag");
375 jQuery_lastModified[ s.url ] = lastModified;
378 jQuery_etag[ s.url ] = etag;
382 if ( s.ifModified && statusText === "notmodified" ) {
388 // Chain data conversions and determine the final value
389 // (if an exception is thrown in the process, it'll be notified as an error)
400 dataTypes = s.dataTypes,
401 converters = s.converters,
407 for( i = 0 ; i < dataTypes.length ; i++ ) {
409 current = dataTypes[ i ];
411 if ( responses[ current ] ) {
412 jXHR[ "response" + responses[ current ] ] = response;
413 responses[ current ] = 0;
418 prev = dataTypes[ i - 1 ];
420 if ( prev !== "*" && current !== "*" && prev !== current ) {
422 conv = converters[ ( conversion = prev + " " + current ) ] ||
423 converters[ "* " + current ];
427 if ( ! conv && prev !== "text" && current !== "text" ) {
428 conv1 = converters[ prev + " text" ] || converters[ "* text" ];
429 conv2 = converters[ "text " + current ];
430 if ( conv1 === true ) {
432 } else if ( conv2 === true ) {
437 if ( ! ( conv || conv1 && conv2 ) ) {
441 if ( conv !== true ) {
442 response = conv ? conv( response ) : conv2( conv1( response ) );
445 } else if ( s.dataFilter ) {
447 response = s.dataFilter( response );
448 dataTypes = s.dataTypes;
452 // We have a real success
458 statusText = "parsererror";
464 } else { // if not success, mark it as an error
466 error = error || statusText;
468 // Set responseText if needed
470 jXHR.responseText = response;
474 // Set data for the fake xhr object
475 jXHR.status = status;
476 jXHR.statusText = statusText;
480 deferred.fire( callbackContext , [ success , statusText , jXHR ] );
482 deferred.fireReject( callbackContext , [ jXHR , statusText , error ] );
486 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ) ,
487 [ jXHR , s , isSuccess ? success : error ] );
491 completeDeferred.fire( callbackContext, [ jXHR , statusText ] );
494 globalEventContext.trigger( "ajaxComplete" , [ jXHR , s] );
495 // Handle the global AJAX counter
496 if ( ! --jQuery.active ) {
497 jQuery.event.trigger( "ajaxStop" );
503 deferred.promise( jXHR );
504 jXHR.success = jXHR.done;
505 jXHR.error = jXHR.fail;
506 jXHR.complete = completeDeferred.done;
508 // Remove hash character (#7531: and string promotion)
509 s.url = ( "" + s.url ).replace( rhash , "" );
511 // Uppercase the type
512 s.type = s.type.toUpperCase();
514 // Determine if request has content
515 s.hasContent = ! rnoContent.test( s.type );
517 // Extract dataTypes list
518 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( /\s+/ );
520 // Determine if a cross-domain request is in order
521 var parts = rurl.exec( s.url.toLowerCase() ),
525 ( parts[ 1 ] && parts[ 1 ] != loc.protocol ||
526 parts[ 2 ] != loc.hostname ||
527 ( parts[ 3 ] || 80 ) != ( loc.port || 80 ) )
530 // Convert data if not already a string
531 if ( s.data && s.processData && typeof s.data != "string" ) {
532 s.data = jQuery.param( s.data , s.traditional );
535 // Watch for a new set of requests
536 if ( s.global && jQuery.active++ === 0 ) {
537 jQuery.event.trigger( "ajaxStart" );
541 transport = jQuery.ajax.prefilter( s ).transport( s );
543 // If no transport, we auto-abort
546 done( 0 , "transport not found" );
551 // More options handling for requests with no content
552 if ( ! s.hasContent ) {
554 // If data is available, append data to url
556 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
559 // Add anti-cache in url if needed
560 if ( s.cache === false ) {
562 var ts = jQuery.now(),
563 // try replacing _= if it is there
564 ret = s.url.replace( rts , "$1_=" + ts );
566 // if nothing was replaced, add timestamp to the end
567 s.url = ret + ( (ret == s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "");
571 // Set the correct header, if data is being sent
572 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
573 requestHeaders[ "content-type" ] = s.contentType;
576 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
577 if ( s.ifModified ) {
578 if ( jQuery_lastModified[ s.url ] ) {
579 requestHeaders[ "if-modified-since" ] = jQuery_lastModified[ s.url ];
581 if ( jQuery_etag[ s.url ] ) {
582 requestHeaders[ "if-none-match" ] = jQuery_etag[ s.url ];
586 // Set the Accepts header for the server, depending on the dataType
587 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
588 s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
591 // Check for headers option
592 for ( i in s.headers ) {
593 requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
596 // Allow custom headers/mimetypes and early abort
597 if ( s.beforeSend && ( s.beforeSend.call( callbackContext , jXHR , s ) === false || state === 2 ) ) {
599 // Abort if not done already
605 // Set state as sending
609 // Install callbacks on deferreds
610 for ( i in { success:1, error:1, complete:1 } ) {
616 globalEventContext.trigger( "ajaxSend" , [ jXHR , s ] );
620 if ( s.async && s.timeout > 0 ) {
621 timeoutTimer = setTimeout(function(){
622 jXHR.abort( "timeout" );
628 transport.send(requestHeaders, done);
630 // Propagate exception as error if not done
631 if ( status === 1 ) {
633 done(0, "error", "" + e);
636 // Simply rethrow otherwise
647 // Serialize an array of form elements or a set of
648 // key/values into a query string
649 param: function( a, traditional ) {
651 add = function( key, value ) {
652 // If value is a function, invoke it and return its value
653 value = jQuery.isFunction(value) ? value() : value;
654 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
657 // Set traditional to true for jQuery <= 1.3.2 behavior.
658 if ( traditional === undefined ) {
659 traditional = jQuery.ajaxSettings.traditional;
662 // If an array was passed in, assume that it is an array of form elements.
663 if ( jQuery.isArray(a) || a.jquery ) {
664 // Serialize the form elements
665 jQuery.each( a, function() {
666 add( this.name, this.value );
670 // If traditional, encode the "old" way (the way 1.3.2 or older
671 // did it), otherwise encode params recursively.
672 for ( var prefix in a ) {
673 buildParams( prefix, a[prefix], traditional, add );
677 // Return the resulting serialization
678 return s.join("&").replace(r20, "+");
682 function buildParams( prefix, obj, traditional, add ) {
683 if ( jQuery.isArray(obj) && obj.length ) {
684 // Serialize array item.
685 jQuery.each( obj, function( i, v ) {
686 if ( traditional || rbracket.test( prefix ) ) {
687 // Treat each array item as a scalar.
691 // If array item is non-scalar (array or object), encode its
692 // numeric index to resolve deserialization ambiguity issues.
693 // Note that rack (as of 1.0.0) can't currently deserialize
694 // nested arrays properly, and attempting to do so may cause
695 // a server error. Possible fixes are to modify rack's
696 // deserialization algorithm or to provide an option or flag
697 // to force array serialization to be shallow.
698 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
702 } else if ( !traditional && obj != null && typeof obj === "object" ) {
703 // If we see an array here, it is empty and should be treated as an empty
705 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
708 // Serialize object item.
710 jQuery.each( obj, function( k, v ) {
711 buildParams( prefix + "[" + k + "]", v, traditional, add );
716 // Serialize scalar item.
721 // This is still on the jQuery object... for now
722 // Want to move this to jQuery.ajax some day
725 // Counter for holding the number of active queries
728 // Last-Modified header cache for next request
734 //Execute or select from functions in a given structure of options
735 function ajax_selectOrExecute( structure , s ) {
737 var dataTypes = s.dataTypes,
745 noSelect = structure !== "transports";
747 function initSearch( dataType ) {
749 flag = transportDataType !== dataType && ! checked[ dataType ];
753 checked[ dataType ] = 1;
754 transportDataType = dataType;
755 list = s[ structure ][ dataType ];
757 length = list ? list.length : 0 ;
763 initSearch( dataTypes[ 0 ] );
765 for ( i = 0 ; ( noSelect || ! selected ) && i <= length ; i++ ) {
767 if ( i === length ) {
773 selected = list[ i ]( s , determineDataType );
775 // If we got redirected to another dataType
776 // Search there (if not in progress or already tried)
777 if ( typeof( selected ) === "string" &&
778 initSearch( selected ) ) {
780 dataTypes.unshift( selected );
786 return noSelect ? jQuery.ajax : selected;
789 // Add an element to one of the structures in ajaxSettings
790 function ajax_addElement( structure , args ) {
794 length = args.length,
805 first = jQuery.type( args[ 0 ] );
807 if ( first === "object" ) {
808 return ajax_selectOrExecute( structure , args[ 0 ] );
811 structure = jQuery.ajaxSettings[ structure ];
813 if ( first !== "function" ) {
815 dataTypes = args[ 0 ].toLowerCase().split(/\s+/);
816 dLength = dataTypes.length;
821 if ( dLength && start < length ) {
823 functors = sliceFunc.call( args , start );
825 for( i = 0 ; i < dLength ; i++ ) {
827 dataType = dataTypes[ i ];
829 first = /^\+/.test( dataType );
832 dataType = dataType.substr(1);
835 if ( dataType !== "" ) {
837 append = Array.prototype[ first ? "unshift" : "push" ];
838 list = structure[ dataType ] = structure[ dataType ] || [];
839 append.apply( list , functors );
848 // Install prefilter & transport methods
849 jQuery.each( [ "prefilter" , "transport" ] , function( _ , name ) {
851 jQuery.ajax[ name ] = function() {
852 return ajax_addElement( _ , arguments );
856 // Utility function that handles dataType when response is received
857 // (for those transports that can give text or xml responses)
858 function determineDataType( s , ct , text , xml ) {
860 var contents = s.contents,
863 dataTypes = s.dataTypes,
864 transportDataType = dataTypes[0],
867 // Auto (xml, json, script or text determined given headers)
868 if ( transportDataType === "*" ) {
870 for ( type in contents ) {
871 if ( ( regexp = contents[ type ] ) && regexp.test( ct ) ) {
872 transportDataType = dataTypes[0] = type;
878 // xml and parsed as such
879 if ( transportDataType === "xml" &&
881 xml.documentElement /* #4958 */ ) {
885 // Text response was provided
890 // If it's not really text, defer to converters
891 if ( transportDataType !== "text" ) {
892 dataTypes.unshift( "text" );
901 * Create the request object; Microsoft failed to properly
902 * implement the XMLHttpRequest in IE7 (can't request local files),
903 * so we use the ActiveXObject when it is available
904 * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
905 * we need a fallback.
907 if ( window.ActiveXObject ) {
908 jQuery.ajaxSettings.xhr = function() {
909 if ( window.location.protocol !== "file:" ) {
911 return new window.XMLHttpRequest();
912 } catch( xhrError ) {}
916 return new window.ActiveXObject("Microsoft.XMLHTTP");
917 } catch( activeError ) {}
921 var testXHR = jQuery.ajaxSettings.xhr();
923 // Does this browser support XHR requests?
924 jQuery.support.ajax = !!testXHR;
926 // Does this browser support crossDomain XHR requests
927 jQuery.support.cors = testXHR && "withCredentials" in testXHR;