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: function( res, status ) {
65 // If successful, inject the HTML into all the matched elements
66 if ( status === "success" || status === "notmodified" ) {
67 // See if a selector was specified
69 // Create a dummy div to hold the results
71 // inject the contents of the document in, removing the scripts
72 // to avoid any 'Permission Denied' errors in IE
73 .append(res.responseText.replace(rscript, ""))
75 // Locate the specified elements
78 // If not, just inject the full result
83 self.each( callback, [res.responseText, status, res] );
91 serialize: function() {
92 return jQuery.param(this.serializeArray());
95 serializeArray: function() {
96 return this.map(function(){
97 return this.elements ? jQuery.makeArray(this.elements) : this;
100 return this.name && !this.disabled &&
101 (this.checked || rselectTextarea.test(this.nodeName) ||
102 rinput.test(this.type));
104 .map(function(i, elem){
105 var val = jQuery(this).val();
109 jQuery.isArray(val) ?
110 jQuery.map( val, function(val, i){
111 return { name: elem.name, value: val.replace(rCRLF, "\r\n") };
113 { name: elem.name, value: val.replace(rCRLF, "\r\n") };
118 // Attach a bunch of functions for handling common AJAX events
119 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function(i,o){
120 jQuery.fn[o] = function(f){
121 return this.bind(o, f);
125 jQuery.each( [ "get", "post" ], function( i, method ) {
126 jQuery[ method ] = function( url, data, callback, type ) {
127 // shift arguments if data argument was omited
128 if ( jQuery.isFunction( data ) ) {
129 type = type || callback;
146 getScript: function( url, callback ) {
147 return jQuery.get(url, null, callback, "script");
150 getJSON: function( url, data, callback ) {
151 return jQuery.get(url, data, callback, "json");
154 ajaxSetup: function( settings ) {
155 jQuery.extend( jQuery.ajaxSettings, settings );
162 contentType: "application/x-www-form-urlencoded",
176 return new window.XMLHttpRequest();
180 xml: "application/xml, text/xml",
183 json: "application/json, text/javascript",
194 // 1) They are useful to introduce custom dataTypes (see transport/jsonp for an example)
195 // 2) These are called:
196 // * BEFORE asking for a transport
197 // * AFTER param serialization (s.data is a string if s.processData is true)
198 // 3) key is the dataType
199 // 4) the catchall symbol "*" can be used
200 // 5) execution will start with transport dataType and THEN continue down to "*" if needed
203 // Transports bindings
204 // 1) key is the dataType
205 // 2) the catchall symbol "*" can be used
206 // 3) selection will start with transport dataType and THEN go to "*" if needed
209 // List of data converters
210 // 1) key format is "source_type destination_type" (a single space in-between)
211 // 2) the catchall symbol "*" can be used for source_type
214 // Convert anything to text
215 "* text": window.String,
217 // Text to html (true = no transformation)
220 // Evaluate text as a json expression
221 "text json": jQuery.parseJSON,
224 "text xml": jQuery.parseXML
229 // (s is used internally)
230 ajax: function( url , options , s ) {
233 if ( arguments.length === 1 ) {
235 url = options ? options.url : undefined;
238 // Force options to be an object
239 options = options || {};
241 // Get the url if provided separately
242 options.url = url || options.url;
244 // Create the final options object
245 s = jQuery.extend( true , {} , jQuery.ajaxSettings , options );
247 // We force the original context
248 // (plain objects used as context get extended)
249 s.context = options.context;
252 jQuery_lastModified = jQuery.lastModified,
253 jQuery_etag = jQuery.etag,
254 // Callbacks contexts
255 callbackContext = s.context || s,
256 globalEventContext = s.context ? jQuery( s.context ) : jQuery.event,
258 deferred = jQuery.Deferred(),
259 completeDeferred = jQuery._Deferred(),
260 // Headers (they are sent all at once)
263 responseHeadersString,
279 setRequestHeader: function(name,value) {
281 requestHeaders[ name.toLowerCase() ] = value;
287 getAllResponseHeaders: function() {
288 return state === 2 ? responseHeadersString : null;
291 // Builds headers hashtable if needed
292 // (match is used internally)
293 getResponseHeader: function( key , match ) {
299 if ( responseHeaders === undefined ) {
301 responseHeaders = {};
303 if ( typeof responseHeadersString === "string" ) {
305 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
306 responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
310 return responseHeaders[ key.toLowerCase() ];
313 // Cancel the request
314 abort: function( statusText ) {
315 if ( transport && state !== 2 ) {
316 transport.abort( statusText || "abort" );
317 done( 0 , statusText );
323 // Callback for when everything is done
324 // It is defined here because jslint complains if it is declared
325 // at the end of the function (which would be more logical and readable)
326 function done( status , statusText , response , headers) {
333 // State is "done" now
337 jXHR.readyState = status ? 4 : 0;
339 // Cache response headers
340 responseHeadersString = headers || "";
342 // Clear timeout if it exists
343 if ( timeoutTimer ) {
344 clearTimeout(timeoutTimer);
349 // and ifModified status
350 ifModified = s.ifModified,
359 // If not timeout, force a jQuery-compliant status text
360 if ( statusText != "timeout" ) {
361 statusText = ( status >= 200 && status < 300 ) ?
363 ( status === 304 ? "notmodified" : "error" );
366 // If successful, handle type chaining
367 if ( statusText === "success" || statusText === "notmodified" ) {
369 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
370 if ( s.ifModified ) {
372 var lastModified = jXHR.getResponseHeader("Last-Modified"),
373 etag = jXHR.getResponseHeader("Etag");
376 jQuery_lastModified[ s.url ] = lastModified;
379 jQuery_etag[ s.url ] = etag;
383 if ( s.ifModified && statusText === "notmodified" ) {
389 // Chain data conversions and determine the final value
390 // (if an exception is thrown in the process, it'll be notified as an error)
401 dataTypes = s.dataTypes,
402 converters = s.converters,
408 for( i = 0 ; i < dataTypes.length ; i++ ) {
410 current = dataTypes[ i ];
412 if ( responses[ current ] ) {
413 jXHR[ "response" + responses[ current ] ] = response;
414 responses[ current ] = 0;
419 prev = dataTypes[ i - 1 ];
421 if ( prev !== "*" && current !== "*" && prev !== current ) {
423 conv = converters[ ( conversion = prev + " " + current ) ] ||
424 converters[ "* " + current ];
428 if ( ! conv && prev !== "text" && current !== "text" ) {
429 conv1 = converters[ prev + " text" ] || converters[ "* text" ];
430 conv2 = converters[ "text " + current ];
431 if ( conv1 === true ) {
433 } else if ( conv2 === true ) {
438 if ( ! ( conv || conv1 && conv2 ) ) {
442 if ( conv !== true ) {
443 response = conv ? conv( response ) : conv2( conv1( response ) );
446 } else if ( s.dataFilter ) {
448 response = s.dataFilter( response );
449 dataTypes = s.dataTypes;
453 // We have a real success
459 statusText = "parsererror";
465 } else { // if not success, mark it as an error
467 error = error || statusText;
469 // Set responseText if needed
471 jXHR.responseText = response;
475 // Set data for the fake xhr object
476 jXHR.status = status;
477 jXHR.statusText = statusText;
481 deferred.fire( callbackContext , [ success , statusText , jXHR ] );
483 deferred.fireReject( callbackContext , [ jXHR , statusText , error ] );
487 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ) ,
488 [ jXHR , s , isSuccess ? success : error ] );
492 completeDeferred.fire( callbackContext, [ jXHR , statusText ] );
495 globalEventContext.trigger( "ajaxComplete" , [ jXHR , s] );
496 // Handle the global AJAX counter
497 if ( ! --jQuery.active ) {
498 jQuery.event.trigger( "ajaxStop" );
504 deferred.promise( jXHR );
505 jXHR.success = jXHR.done;
506 jXHR.error = jXHR.fail;
507 jXHR.complete = completeDeferred.done;
509 // Remove hash character (#7531: and string promotion)
510 s.url = ( "" + s.url ).replace( rhash , "" );
512 // Uppercase the type
513 s.type = s.type.toUpperCase();
515 // Determine if request has content
516 s.hasContent = ! rnoContent.test( s.type );
518 // Extract dataTypes list
519 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( /\s+/ );
521 // Determine if a cross-domain request is in order
522 var parts = rurl.exec( s.url.toLowerCase() ),
525 if ( ! s.crossDomain ) {
528 ( parts[ 1 ] && parts[ 1 ] != loc.protocol ||
529 parts[ 2 ] != loc.hostname ||
530 ( parts[ 3 ] || 80 ) != ( loc.port || 80 ) )
534 // Convert data if not already a string
535 if ( s.data && s.processData && typeof s.data != "string" ) {
536 s.data = jQuery.param( s.data , s.traditional );
540 transport = jQuery.ajax.prefilter( s , options ).transport( s );
542 // Watch for a new set of requests
543 if ( s.global && jQuery.active++ === 0 ) {
544 jQuery.event.trigger( "ajaxStart" );
547 // If no transport, we auto-abort
550 done( 0 , "transport not found" );
555 // More options handling for requests with no content
556 if ( ! s.hasContent ) {
558 // If data is available, append data to url
560 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
563 // Add anti-cache in url if needed
564 if ( s.cache === false ) {
566 var ts = jQuery.now(),
567 // try replacing _= if it is there
568 ret = s.url.replace( rts , "$1_=" + ts );
570 // if nothing was replaced, add timestamp to the end
571 s.url = ret + ( (ret == s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "");
575 // Set the correct header, if data is being sent
576 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
577 requestHeaders[ "content-type" ] = s.contentType;
580 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
581 if ( s.ifModified ) {
582 if ( jQuery_lastModified[ s.url ] ) {
583 requestHeaders[ "if-modified-since" ] = jQuery_lastModified[ s.url ];
585 if ( jQuery_etag[ s.url ] ) {
586 requestHeaders[ "if-none-match" ] = jQuery_etag[ s.url ];
590 // Set the Accepts header for the server, depending on the dataType
591 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
592 s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
595 // Check for headers option
596 for ( i in s.headers ) {
597 requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
600 // Allow custom headers/mimetypes and early abort
601 if ( s.beforeSend && ( s.beforeSend.call( callbackContext , jXHR , s ) === false || state === 2 ) ) {
603 // Abort if not done already
609 // Set state as sending
613 // Install callbacks on deferreds
614 for ( i in { success:1, error:1, complete:1 } ) {
620 globalEventContext.trigger( "ajaxSend" , [ jXHR , s ] );
624 if ( s.async && s.timeout > 0 ) {
625 timeoutTimer = setTimeout(function(){
626 jXHR.abort( "timeout" );
632 transport.send(requestHeaders, done);
634 // Propagate exception as error if not done
635 if ( status === 1 ) {
637 done(0, "error", "" + e);
640 // Simply rethrow otherwise
651 // Serialize an array of form elements or a set of
652 // key/values into a query string
653 param: function( a, traditional ) {
655 add = function( key, value ) {
656 // If value is a function, invoke it and return its value
657 value = jQuery.isFunction(value) ? value() : value;
658 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
661 // Set traditional to true for jQuery <= 1.3.2 behavior.
662 if ( traditional === undefined ) {
663 traditional = jQuery.ajaxSettings.traditional;
666 // If an array was passed in, assume that it is an array of form elements.
667 if ( jQuery.isArray(a) || a.jquery ) {
668 // Serialize the form elements
669 jQuery.each( a, function() {
670 add( this.name, this.value );
674 // If traditional, encode the "old" way (the way 1.3.2 or older
675 // did it), otherwise encode params recursively.
676 for ( var prefix in a ) {
677 buildParams( prefix, a[prefix], traditional, add );
681 // Return the resulting serialization
682 return s.join("&").replace(r20, "+");
686 function buildParams( prefix, obj, traditional, add ) {
687 if ( jQuery.isArray(obj) && obj.length ) {
688 // Serialize array item.
689 jQuery.each( obj, function( i, v ) {
690 if ( traditional || rbracket.test( prefix ) ) {
691 // Treat each array item as a scalar.
695 // If array item is non-scalar (array or object), encode its
696 // numeric index to resolve deserialization ambiguity issues.
697 // Note that rack (as of 1.0.0) can't currently deserialize
698 // nested arrays properly, and attempting to do so may cause
699 // a server error. Possible fixes are to modify rack's
700 // deserialization algorithm or to provide an option or flag
701 // to force array serialization to be shallow.
702 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
706 } else if ( !traditional && obj != null && typeof obj === "object" ) {
707 // If we see an array here, it is empty and should be treated as an empty
709 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
712 // Serialize object item.
714 jQuery.each( obj, function( k, v ) {
715 buildParams( prefix + "[" + k + "]", v, traditional, add );
720 // Serialize scalar item.
725 // This is still on the jQuery object... for now
726 // Want to move this to jQuery.ajax some day
729 // Counter for holding the number of active queries
732 // Last-Modified header cache for next request
738 //Execute or select from functions in a given structure of options
739 function ajax_selectOrExecute( structure , s ) {
741 var dataTypes = s.dataTypes,
749 noSelect = structure !== "transports";
751 function initSearch( dataType ) {
753 flag = transportDataType !== dataType && ! checked[ dataType ];
757 checked[ dataType ] = 1;
758 transportDataType = dataType;
759 list = s[ structure ][ dataType ];
761 length = list ? list.length : 0 ;
767 initSearch( dataTypes[ 0 ] );
769 for ( i = 0 ; ( noSelect || ! selected ) && i <= length ; i++ ) {
771 if ( i === length ) {
777 selected = list[ i ]( s , determineDataType );
779 // If we got redirected to another dataType
780 // Search there (if not in progress or already tried)
781 if ( typeof( selected ) === "string" &&
782 initSearch( selected ) ) {
784 dataTypes.unshift( selected );
790 return noSelect ? jQuery.ajax : selected;
793 // Add an element to one of the structures in ajaxSettings
794 function ajax_addElement( structure , args ) {
798 length = args.length,
809 first = jQuery.type( args[ 0 ] );
811 if ( first === "object" ) {
812 return ajax_selectOrExecute( structure , args[ 0 ] );
815 structure = jQuery.ajaxSettings[ structure ];
817 if ( first !== "function" ) {
819 dataTypes = args[ 0 ].toLowerCase().split(/\s+/);
820 dLength = dataTypes.length;
825 if ( dLength && start < length ) {
827 functors = sliceFunc.call( args , start );
829 for( i = 0 ; i < dLength ; i++ ) {
831 dataType = dataTypes[ i ];
833 first = /^\+/.test( dataType );
836 dataType = dataType.substr(1);
839 if ( dataType !== "" ) {
841 append = Array.prototype[ first ? "unshift" : "push" ];
842 list = structure[ dataType ] = structure[ dataType ] || [];
843 append.apply( list , functors );
852 // Install prefilter & transport methods
853 jQuery.each( [ "prefilter" , "transport" ] , function( _ , name ) {
855 jQuery.ajax[ name ] = function() {
856 return ajax_addElement( _ , arguments );
860 // Utility function that handles dataType when response is received
861 // (for those transports that can give text or xml responses)
862 function determineDataType( s , ct , text , xml ) {
864 var contents = s.contents,
867 dataTypes = s.dataTypes,
868 transportDataType = dataTypes[0],
871 // Auto (xml, json, script or text determined given headers)
872 if ( transportDataType === "*" ) {
874 for ( type in contents ) {
875 if ( ( regexp = contents[ type ] ) && regexp.test( ct ) ) {
876 transportDataType = dataTypes[0] = type;
882 // xml and parsed as such
883 if ( transportDataType === "xml" &&
885 xml.documentElement /* #4958 */ ) {
889 // Text response was provided
894 // If it's not really text, defer to converters
895 if ( transportDataType !== "text" ) {
896 dataTypes.unshift( "text" );
905 * Create the request object; Microsoft failed to properly
906 * implement the XMLHttpRequest in IE7 (can't request local files),
907 * so we use the ActiveXObject when it is available
908 * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
909 * we need a fallback.
911 if ( window.ActiveXObject ) {
912 jQuery.ajaxSettings.xhr = function() {
913 if ( window.location.protocol !== "file:" ) {
915 return new window.XMLHttpRequest();
916 } catch( xhrError ) {}
920 return new window.ActiveXObject("Microsoft.XMLHTTP");
921 } catch( activeError ) {}
925 var testXHR = jQuery.ajaxSettings.xhr();
927 // Does this browser support XHR requests?
928 jQuery.support.ajax = !!testXHR;
930 // Does this browser support crossDomain XHR requests
931 jQuery.support.cors = testXHR && "withCredentials" in testXHR;