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",
186 return new window.XMLHttpRequest();
190 xml: "application/xml, text/xml",
193 json: "application/json, text/javascript",
204 // 1) They are useful to introduce custom dataTypes (see transport/jsonp for an example)
205 // 2) These are called:
206 // * BEFORE asking for a transport
207 // * AFTER param serialization (s.data is a string if s.processData is true)
208 // 3) key is the dataType
209 // 4) the catchall symbol "*" can be used
210 // 5) execution will start with transport dataType and THEN continue down to "*" if needed
213 // Transports bindings
214 // 1) key is the dataType
215 // 2) the catchall symbol "*" can be used
216 // 3) selection will start with transport dataType and THEN go to "*" if needed
219 // List of data converters
220 // 1) key format is "source_type destination_type" (a single space in-between)
221 // 2) the catchall symbol "*" can be used for source_type
224 // Convert anything to text
225 "* text": window.String,
227 // Text to html (true = no transformation)
230 // Evaluate text as a json expression
231 "text json": jQuery.parseJSON,
234 "text xml": jQuery.parseXML
239 // (s is used internally)
240 ajax: function( url , options , s ) {
243 if ( arguments.length === 1 ) {
245 url = options ? options.url : undefined;
248 // Force options to be an object
249 options = options || {};
251 // Get the url if provided separately
252 options.url = url || options.url;
254 // Create the final options object
255 s = jQuery.extend( true , {} , jQuery.ajaxSettings , options );
257 // We force the original context
258 // (plain objects used as context get extended)
259 s.context = options.context;
262 jQuery_lastModified = jQuery.lastModified,
263 jQuery_etag = jQuery.etag,
264 // Callbacks contexts
265 callbackContext = s.context || s,
266 globalEventContext = s.context ? jQuery( s.context ) : jQuery.event,
268 deferred = jQuery.Deferred(),
269 completeDeferred = jQuery._Deferred(),
270 // Status-dependent callbacks
271 statusCode = s.statusCode || {},
272 // Headers (they are sent all at once)
275 responseHeadersString,
281 // Cross-domain detection vars
282 loc = document.location,
294 setRequestHeader: function(name,value) {
296 requestHeaders[ name.toLowerCase() ] = value;
302 getAllResponseHeaders: function() {
303 return state === 2 ? responseHeadersString : null;
306 // Builds headers hashtable if needed
307 // (match is used internally)
308 getResponseHeader: function( key , match ) {
312 if ( responseHeaders === undefined ) {
314 responseHeaders = {};
316 if ( typeof responseHeadersString === "string" ) {
318 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
319 responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
323 match = responseHeaders[ key.toLowerCase() ];
333 // Cancel the request
334 abort: function( statusText ) {
336 transport.abort( statusText || "abort" );
338 done( 0 , statusText );
343 // Callback for when everything is done
344 // It is defined here because jslint complains if it is declared
345 // at the end of the function (which would be more logical and readable)
346 function done( status , statusText , response , headers) {
353 // State is "done" now
356 // Dereference transport for early garbage collection
357 // (no matter how long the jXHR transport will be used
361 jXHR.readyState = status ? 4 : 0;
363 // Cache response headers
364 responseHeadersString = headers || "";
366 // Clear timeout if it exists
367 if ( timeoutTimer ) {
368 clearTimeout(timeoutTimer);
373 // and ifModified status
374 ifModified = s.ifModified,
383 // If successful, handle type chaining
384 if ( status >= 200 && status < 300 || status === 304 ) {
386 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
387 if ( s.ifModified ) {
389 var lastModified = jXHR.getResponseHeader("Last-Modified"),
390 etag = jXHR.getResponseHeader("Etag");
393 jQuery_lastModified[ s.url ] = lastModified;
396 jQuery_etag[ s.url ] = etag;
401 if ( status === 304 ) {
403 // Set the statusText accordingly
404 statusText = "notmodified";
411 // Set the statusText accordingly
412 statusText = "success";
414 // Chain data conversions and determine the final value
415 // (if an exception is thrown in the process, it'll be notified as an error)
423 // Conversion function
425 // Conversion functions (when text is used in-between)
428 // Local references to dataTypes & converters
429 dataTypes = s.dataTypes,
430 converters = s.converters,
431 // DataType to responseXXX field mapping
437 // For each dataType in the chain
438 for( i = 0 ; i < dataTypes.length ; i++ ) {
440 current = dataTypes[ i ];
442 // If a responseXXX field for this dataType exists
443 // and if it hasn't been set yet
444 if ( responses[ current ] ) {
446 jXHR[ "response" + responses[ current ] ] = response;
448 responses[ current ] = 0;
451 // If this is not the first element
454 // Get the dataType to convert from
455 prev = dataTypes[ i - 1 ];
457 // If no catch-all and dataTypes are actually different
458 if ( prev !== "*" && current !== "*" && prev !== current ) {
461 conv = converters[ prev + " " + current ] ||
462 converters[ "* " + current ];
466 // If there is no direct converter and none of the dataTypes is text
467 if ( ! conv && prev !== "text" && current !== "text" ) {
468 // Try with text in-between
469 conv1 = converters[ prev + " text" ] || converters[ "* text" ];
470 conv2 = converters[ "text " + current ];
471 // Revert back to a single converter
472 // if one of the converter is an equivalence
473 if ( conv1 === true ) {
475 } else if ( conv2 === true ) {
479 // If we found no converter, dispatch an error
480 if ( ! ( conv || conv1 && conv2 ) ) {
483 // If found converter is not an equivalence
484 if ( conv !== true ) {
485 // Convert with 1 or 2 converters accordingly
486 response = conv ? conv( response ) : conv2( conv1( response ) );
489 // If it is the first element of the chain
490 // and we have a dataFilter
491 } else if ( s.dataFilter ) {
492 // Apply the dataFilter
493 response = s.dataFilter( response , current );
494 // Get dataTypes again in case the filter changed them
495 dataTypes = s.dataTypes;
500 // We have a real success
504 // If an exception was thrown
507 // We have a parsererror
508 statusText = "parsererror";
514 // if not success, mark it as an error
517 error = statusText = statusText || "error";
519 // Set responseText if needed
521 jXHR.responseText = response;
525 // Set data for the fake xhr object
526 jXHR.status = status;
527 jXHR.statusText = statusText;
531 deferred.fire( callbackContext , [ success , statusText , jXHR ] );
533 deferred.fireReject( callbackContext , [ jXHR , statusText , error ] );
536 // Status-dependent callbacks
537 jXHR.statusCode( statusCode );
540 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ) ,
541 [ jXHR , s , isSuccess ? success : error ] );
545 completeDeferred.fire( callbackContext, [ jXHR , statusText ] );
548 globalEventContext.trigger( "ajaxComplete" , [ jXHR , s] );
549 // Handle the global AJAX counter
550 if ( ! --jQuery.active ) {
551 jQuery.event.trigger( "ajaxStop" );
557 deferred.promise( jXHR );
558 jXHR.success = jXHR.done;
559 jXHR.error = jXHR.fail;
560 jXHR.complete = completeDeferred.done;
562 // Status-dependent callbacks
563 jXHR.statusCode = function( map ) {
565 var resolved = jXHR.isResolved(),
567 if ( resolved || jXHR.isRejected() ) {
568 tmp = map[ jXHR.status ];
570 if ( map === statusCode ) {
571 delete statusCode[ jXHR.status ];
573 jXHR[ resolved ? "done" : "fail" ]( tmp );
577 statusCode[ tmp ] = [ statusCode[ tmp ] , map[ tmp ] ];
584 // Remove hash character (#7531: and string promotion)
585 s.url = ( "" + s.url ).replace( rhash , "" );
587 // Extract dataTypes list
588 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( /\s+/ );
590 // Determine if a cross-domain request is in order
591 if ( ! s.crossDomain ) {
592 parts = rurl.exec( s.url.toLowerCase() );
595 ( parts[ 1 ] && parts[ 1 ] != loc.protocol ||
596 parts[ 2 ] != loc.hostname ||
597 ( parts[ 3 ] || 80 ) != ( loc.port || 80 ) )
601 // Convert data if not already a string
602 if ( s.data && s.processData && typeof s.data !== "string" ) {
603 s.data = jQuery.param( s.data , s.traditional );
607 jQuery.ajaxPrefilter( s , options );
609 // Uppercase the type
610 s.type = s.type.toUpperCase();
612 // Determine if request has content
613 s.hasContent = ! rnoContent.test( s.type );
615 // Watch for a new set of requests
616 if ( s.global && jQuery.active++ === 0 ) {
617 jQuery.event.trigger( "ajaxStart" );
620 // More options handling for requests with no content
621 if ( ! s.hasContent ) {
623 // If data is available, append data to url
625 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
628 // Add anti-cache in url if needed
629 if ( s.cache === false ) {
631 var ts = jQuery.now(),
632 // try replacing _= if it is there
633 ret = s.url.replace( rts , "$1_=" + ts );
635 // if nothing was replaced, add timestamp to the end
636 s.url = ret + ( (ret == s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "");
640 // Set the correct header, if data is being sent
641 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
642 requestHeaders[ "content-type" ] = s.contentType;
645 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
646 if ( s.ifModified ) {
647 if ( jQuery_lastModified[ s.url ] ) {
648 requestHeaders[ "if-modified-since" ] = jQuery_lastModified[ s.url ];
650 if ( jQuery_etag[ s.url ] ) {
651 requestHeaders[ "if-none-match" ] = jQuery_etag[ s.url ];
655 // Set the Accepts header for the server, depending on the dataType
656 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
657 s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
660 // Check for headers option
661 for ( i in s.headers ) {
662 requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
665 // Allow custom headers/mimetypes and early abort
666 if ( s.beforeSend && ( s.beforeSend.call( callbackContext , jXHR , s ) === false || state === 2 ) ) {
668 // Abort if not done already
676 // Install callbacks on deferreds
677 for ( i in { success:1, error:1, complete:1 } ) {
682 transport = jQuery.ajaxTransport( s );
684 // If no transport, we auto-abort
687 done( 0 , "notransport" );
691 // Set state as sending
692 state = jXHR.readyState = 1;
696 globalEventContext.trigger( "ajaxSend" , [ jXHR , s ] );
700 if ( s.async && s.timeout > 0 ) {
701 timeoutTimer = setTimeout(function(){
702 jXHR.abort( "timeout" );
708 transport.send(requestHeaders, done);
710 // Propagate exception as error if not done
711 if ( status === 1 ) {
713 done(0, "error", "" + e);
716 // Simply rethrow otherwise
727 // Serialize an array of form elements or a set of
728 // key/values into a query string
729 param: function( a, traditional ) {
731 add = function( key, value ) {
732 // If value is a function, invoke it and return its value
733 value = jQuery.isFunction(value) ? value() : value;
734 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
737 // Set traditional to true for jQuery <= 1.3.2 behavior.
738 if ( traditional === undefined ) {
739 traditional = jQuery.ajaxSettings.traditional;
742 // If an array was passed in, assume that it is an array of form elements.
743 if ( jQuery.isArray(a) || a.jquery ) {
744 // Serialize the form elements
745 jQuery.each( a, function() {
746 add( this.name, this.value );
750 // If traditional, encode the "old" way (the way 1.3.2 or older
751 // did it), otherwise encode params recursively.
752 for ( var prefix in a ) {
753 buildParams( prefix, a[prefix], traditional, add );
757 // Return the resulting serialization
758 return s.join("&").replace(r20, "+");
762 function buildParams( prefix, obj, traditional, add ) {
763 if ( jQuery.isArray(obj) && obj.length ) {
764 // Serialize array item.
765 jQuery.each( obj, function( i, v ) {
766 if ( traditional || rbracket.test( prefix ) ) {
767 // Treat each array item as a scalar.
771 // If array item is non-scalar (array or object), encode its
772 // numeric index to resolve deserialization ambiguity issues.
773 // Note that rack (as of 1.0.0) can't currently deserialize
774 // nested arrays properly, and attempting to do so may cause
775 // a server error. Possible fixes are to modify rack's
776 // deserialization algorithm or to provide an option or flag
777 // to force array serialization to be shallow.
778 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
782 } else if ( !traditional && obj != null && typeof obj === "object" ) {
783 // If we see an array here, it is empty and should be treated as an empty
785 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
788 // Serialize object item.
790 jQuery.each( obj, function( k, v ) {
791 buildParams( prefix + "[" + k + "]", v, traditional, add );
796 // Serialize scalar item.
801 // This is still on the jQuery object... for now
802 // Want to move this to jQuery.ajax some day
805 // Counter for holding the number of active queries
808 // Last-Modified header cache for next request
814 //Execute or select from functions in a given structure of options
815 function ajax_selectOrExecute( structure , s ) {
817 var dataTypes = s.dataTypes,
825 noSelect = structure !== "transports";
827 function initSearch( dataType ) {
829 flag = transportDataType !== dataType && ! checked[ dataType ];
833 checked[ dataType ] = 1;
834 transportDataType = dataType;
835 list = s[ structure ][ dataType ];
837 length = list ? list.length : 0 ;
843 initSearch( dataTypes[ 0 ] );
845 for ( i = 0 ; ( noSelect || ! selected ) && i <= length ; i++ ) {
847 if ( i === length ) {
853 selected = list[ i ]( s , determineDataType );
855 // If we got redirected to another dataType
856 // Search there (if not in progress or already tried)
857 if ( typeof( selected ) === "string" &&
858 initSearch( selected ) ) {
860 dataTypes.unshift( selected );
866 return noSelect ? jQuery : selected;
869 // Add an element to one of the structures in ajaxSettings
870 function ajax_addElement( structure , args ) {
874 length = args.length,
885 first = jQuery.type( args[ 0 ] );
887 if ( first === "object" ) {
888 return ajax_selectOrExecute( structure , args[ 0 ] );
891 structure = jQuery.ajaxSettings[ structure ];
893 if ( first !== "function" ) {
895 dataTypes = args[ 0 ].toLowerCase().split(/\s+/);
896 dLength = dataTypes.length;
901 if ( dLength && start < length ) {
903 functors = sliceFunc.call( args , start );
905 for( i = 0 ; i < dLength ; i++ ) {
907 dataType = dataTypes[ i ];
909 first = /^\+/.test( dataType );
912 dataType = dataType.substr(1);
915 if ( dataType !== "" ) {
917 append = Array.prototype[ first ? "unshift" : "push" ];
918 list = structure[ dataType ] = structure[ dataType ] || [];
919 append.apply( list , functors );
928 // Install prefilter & transport methods
929 jQuery.each( [ "Prefilter" , "Transport" ] , function( _ , name ) {
930 _ = name.toLowerCase() + "s";
931 jQuery[ "ajax" + name ] = function() {
932 return ajax_addElement( _ , arguments );
936 // Utility function that handles dataType when response is received
937 // (for those transports that can give text or xml responses)
938 function determineDataType( s , ct , text , xml ) {
940 var contents = s.contents,
943 dataTypes = s.dataTypes,
944 transportDataType = dataTypes[0],
947 // Auto (xml, json, script or text determined given headers)
948 if ( transportDataType === "*" ) {
950 for ( type in contents ) {
951 if ( ( regexp = contents[ type ] ) && regexp.test( ct ) ) {
952 transportDataType = dataTypes[0] = type;
958 // xml and parsed as such
959 if ( transportDataType === "xml" &&
961 xml.documentElement /* #4958 */ ) {
965 // Text response was provided
970 // If it's not really text, defer to converters
971 if ( transportDataType !== "text" ) {
972 dataTypes.unshift( "text" );
981 * Create the request object; Microsoft failed to properly
982 * implement the XMLHttpRequest in IE7 (can't request local files),
983 * so we use the ActiveXObject when it is available
984 * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
985 * we need a fallback.
987 if ( window.ActiveXObject ) {
988 jQuery.ajaxSettings.xhr = function() {
989 if ( window.location.protocol !== "file:" ) {
991 return new window.XMLHttpRequest();
992 } catch( xhrError ) {}
996 return new window.ActiveXObject("Microsoft.XMLHTTP");
997 } catch( activeError ) {}
1001 var testXHR = jQuery.ajaxSettings.xhr();
1003 // Does this browser support XHR requests?
1004 jQuery.support.ajax = !!testXHR;
1006 // Does this browser support crossDomain XHR requests
1007 jQuery.support.cors = testXHR && "withCredentials" in testXHR;