7 rheaders = /^(.*?):\s*(.*?)\r?$/mg, // IE leaves an \r character at EOL
8 rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
9 rnoContent = /^(?:GET|HEAD)$/,
11 rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
12 rselectTextarea = /^(?:select|textarea)/i,
14 rts = /([?&])_=[^&]*/,
15 rurl = /^(\w+:)?\/\/([^\/?#:]+)(?::(\d+))?/,
18 sliceFunc = Array.prototype.slice,
20 // Keep a copy of the old load method
21 _load = jQuery.fn.load,
24 // 1) They are useful to introduce custom dataTypes (see transport/jsonp for an example)
25 // 2) These are called:
26 // * BEFORE asking for a transport
27 // * AFTER param serialization (s.data is a string if s.processData is true)
28 // 3) key is the dataType
29 // 4) the catchall symbol "*" can be used
30 // 5) execution will start with transport dataType and THEN continue down to "*" if needed
33 // Transports bindings
34 // 1) key is the dataType
35 // 2) the catchall symbol "*" can be used
36 // 3) selection will start with transport dataType and THEN go to "*" if needed
40 load: function( url, params, callback ) {
41 if ( typeof url !== "string" && _load ) {
42 return _load.apply( this, arguments );
44 // Don't do a request if no elements are being requested
45 } else if ( !this.length ) {
49 var off = url.indexOf(" ");
51 var selector = url.slice(off, url.length);
52 url = url.slice(0, off);
55 // Default to a GET request
58 // If the second parameter was provided
61 if ( jQuery.isFunction( params ) ) {
62 // We assume that it's the callback
66 // Otherwise, build a param string
67 } else if ( typeof params === "object" ) {
68 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
75 // Request the remote document
81 // Complete callback (responseText is used internally)
82 complete: function( jXHR, status, responseText ) {
83 // Store the response as specified by the jXHR object
84 responseText = jXHR.responseText;
85 // If successful, inject the HTML into all the matched elements
86 if ( jXHR.isResolved() ) {
87 // #4825: Get the actual response in case
88 // a dataFilter is present in ajaxSettings
89 jXHR.done(function( r ) {
92 // See if a selector was specified
94 // Create a dummy div to hold the results
96 // inject the contents of the document in, removing the scripts
97 // to avoid any 'Permission Denied' errors in IE
98 .append(responseText.replace(rscript, ""))
100 // Locate the specified elements
103 // If not, just inject the full result
108 self.each( callback, [responseText, status, jXHR] );
116 serialize: function() {
117 return jQuery.param(this.serializeArray());
120 serializeArray: function() {
121 return this.map(function(){
122 return this.elements ? jQuery.makeArray(this.elements) : this;
125 return this.name && !this.disabled &&
126 (this.checked || rselectTextarea.test(this.nodeName) ||
127 rinput.test(this.type));
129 .map(function(i, elem){
130 var val = jQuery(this).val();
134 jQuery.isArray(val) ?
135 jQuery.map( val, function(val, i){
136 return { name: elem.name, value: val.replace(rCRLF, "\r\n") };
138 { name: elem.name, value: val.replace(rCRLF, "\r\n") };
143 // Attach a bunch of functions for handling common AJAX events
144 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function(i,o){
145 jQuery.fn[o] = function(f){
146 return this.bind(o, f);
150 jQuery.each( [ "get", "post" ], function( i, method ) {
151 jQuery[ method ] = function( url, data, callback, type ) {
152 // shift arguments if data argument was omited
153 if ( jQuery.isFunction( data ) ) {
154 type = type || callback;
171 getScript: function( url, callback ) {
172 return jQuery.get(url, null, callback, "script");
175 getJSON: function( url, data, callback ) {
176 return jQuery.get(url, data, callback, "json");
179 ajaxSetup: function( settings ) {
180 jQuery.extend( true, jQuery.ajaxSettings, settings );
181 if ( settings.context ) {
182 jQuery.ajaxSettings.context = settings.context;
190 contentType: "application/x-www-form-urlencoded",
206 xml: "application/xml, text/xml",
209 json: "application/json, text/javascript",
224 // List of data converters
225 // 1) key format is "source_type destination_type" (a single space in-between)
226 // 2) the catchall symbol "*" can be used for source_type
229 // Convert anything to text
230 "* text": window.String,
232 // Text to html (true = no transformation)
235 // Evaluate text as a json expression
236 "text json": jQuery.parseJSON,
239 "text xml": jQuery.parseXML
243 ajaxPrefilter: function( a , b ) {
244 prefiltersOrTransports( prefilters , a , b );
247 ajaxTransport: function( a , b ) {
248 return prefiltersOrTransports( transports , a , b );
252 ajax: function( url , options ) {
254 // If options is not an object,
255 // we simulate pre-1.5 signature
256 if ( typeof( options ) !== "object" ) {
261 // Force options to be an object
262 options = options || {};
264 var // Create the final options object
265 s = jQuery.extend( true , {} , jQuery.ajaxSettings , options ),
266 // Callbacks contexts
267 // We force the original context if it exists
268 // or take it from jQuery.ajaxSettings otherwise
269 // (plain objects used as context get extended)
271 ( s.context = ( "context" in options ? options : jQuery.ajaxSettings ).context ) || s,
272 globalEventContext = callbackContext === s ? jQuery.event : jQuery( callbackContext ),
274 deferred = jQuery.Deferred(),
275 completeDeferred = jQuery._Deferred(),
276 // Status-dependent callbacks
277 statusCode = s.statusCode || {},
278 // Headers (they are sent all at once)
281 responseHeadersString,
287 // Cross-domain detection vars
288 loc = document.location,
289 protocol = loc.protocol || "http:",
301 setRequestHeader: function(name,value) {
303 requestHeaders[ name.toLowerCase() ] = value;
309 getAllResponseHeaders: function() {
310 return state === 2 ? responseHeadersString : null;
313 // Builds headers hashtable if needed
314 getResponseHeader: function( key ) {
317 if ( !responseHeaders ) {
318 responseHeaders = {};
319 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
320 responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
323 match = responseHeaders[ key.toLowerCase() ];
325 return match || null;
328 // Cancel the request
329 abort: function( statusText ) {
331 transport.abort( statusText || "abort" );
333 done( 0 , statusText );
338 // Callback for when everything is done
339 // It is defined here because jslint complains if it is declared
340 // at the end of the function (which would be more logical and readable)
341 function done( status , statusText , responses , headers) {
348 // State is "done" now
351 // Clear timeout if it exists
352 if ( timeoutTimer ) {
353 clearTimeout(timeoutTimer);
356 // Dereference transport for early garbage collection
357 // (no matter how long the jXHR object will be used)
358 transport = undefined;
360 // Cache response headers
361 responseHeadersString = headers || "";
364 jXHR.readyState = status ? 4 : 0;
368 error = ( statusText = statusText || "error" ),
369 response = responses ? ajaxHandleResponses( s , jXHR , responses ) : undefined,
373 // If successful, handle type chaining
374 if ( status >= 200 && status < 300 || status === 304 ) {
376 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
377 if ( s.ifModified ) {
379 if ( ( lastModified = jXHR.getResponseHeader("Last-Modified") ) ) {
380 jQuery.lastModified[ s.url ] = lastModified;
382 if ( ( etag = jXHR.getResponseHeader("Etag") ) ) {
383 jQuery.etag[ s.url ] = etag;
388 if ( status === 304 ) {
390 statusText = "notmodified";
397 success = ajaxConvert( s , response );
398 statusText = "success";
401 // We have a parsererror
402 statusText = "parsererror";
408 // Set data for the fake xhr object
409 jXHR.status = status;
410 jXHR.statusText = statusText;
414 deferred.resolveWith( callbackContext , [ success , statusText , jXHR ] );
416 deferred.rejectWith( callbackContext , [ jXHR , statusText , error ] );
419 // Status-dependent callbacks
420 jXHR.statusCode( statusCode );
421 statusCode = undefined;
424 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ) ,
425 [ jXHR , s , isSuccess ? success : error ] );
429 completeDeferred.resolveWith( callbackContext, [ jXHR , statusText ] );
432 globalEventContext.trigger( "ajaxComplete" , [ jXHR , s] );
433 // Handle the global AJAX counter
434 if ( ! --jQuery.active ) {
435 jQuery.event.trigger( "ajaxStop" );
441 deferred.promise( jXHR );
442 jXHR.success = jXHR.done;
443 jXHR.error = jXHR.fail;
444 jXHR.complete = completeDeferred.done;
446 // Status-dependent callbacks
447 jXHR.statusCode = function( map ) {
452 statusCode[ tmp ] = [ statusCode[ tmp ] , map[ tmp ] ];
455 tmp = map[ jXHR.status ];
456 jXHR.then( tmp , tmp );
462 // Remove hash character (#7531: and string promotion)
463 // We also use the url parameter if available
464 s.url = ( "" + ( url || s.url ) ).replace( rhash , "" );
466 // Extract dataTypes list
467 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
469 // Determine if a cross-domain request is in order
470 if ( ! s.crossDomain ) {
471 parts = rurl.exec( s.url.toLowerCase() );
474 ( parts[ 1 ] && parts[ 1 ] != protocol ||
475 parts[ 2 ] != loc.hostname ||
476 ( parts[ 3 ] || ( ( parts[ 1 ] || protocol ) === "http:" ? 80 : 443 ) ) !=
477 ( loc.port || ( protocol === "http:" ? 80 : 443 ) ) )
481 // Convert data if not already a string
482 if ( s.data && s.processData && typeof s.data !== "string" ) {
483 s.data = jQuery.param( s.data , s.traditional );
487 jQuery.ajaxPrefilter( s , options );
489 // Uppercase the type
490 s.type = s.type.toUpperCase();
492 // Determine if request has content
493 s.hasContent = ! rnoContent.test( s.type );
495 // Watch for a new set of requests
496 if ( s.global && jQuery.active++ === 0 ) {
497 jQuery.event.trigger( "ajaxStart" );
500 // More options handling for requests with no content
501 if ( ! s.hasContent ) {
503 // If data is available, append data to url
505 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
508 // Add anti-cache in url if needed
509 if ( s.cache === false ) {
511 var ts = jQuery.now(),
512 // try replacing _= if it is there
513 ret = s.url.replace( rts , "$1_=" + ts );
515 // if nothing was replaced, add timestamp to the end
516 s.url = ret + ( (ret == s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "");
520 // Set the correct header, if data is being sent
521 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
522 requestHeaders[ "content-type" ] = s.contentType;
525 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
526 if ( s.ifModified ) {
527 if ( jQuery.lastModified[ s.url ] ) {
528 requestHeaders[ "if-modified-since" ] = jQuery.lastModified[ s.url ];
530 if ( jQuery.etag[ s.url ] ) {
531 requestHeaders[ "if-none-match" ] = jQuery.etag[ s.url ];
535 // Set the Accepts header for the server, depending on the dataType
536 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
537 s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
540 // Check for headers option
541 for ( i in s.headers ) {
542 requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
545 // Allow custom headers/mimetypes and early abort
546 if ( s.beforeSend && ( s.beforeSend.call( callbackContext , jXHR , s ) === false || state === 2 ) ) {
548 // Abort if not done already
556 // Install callbacks on deferreds
557 for ( i in { success:1, error:1, complete:1 } ) {
562 transport = jQuery.ajaxTransport( s , options );
564 // If no transport, we auto-abort
566 done( 0 , "notransport" );
569 // Set state as sending
570 state = jXHR.readyState = 1;
574 globalEventContext.trigger( "ajaxSend" , [ jXHR , s ] );
578 if ( s.async && s.timeout > 0 ) {
579 timeoutTimer = setTimeout(function(){
580 jXHR.abort( "timeout" );
585 transport.send(requestHeaders, done);
587 // Propagate exception as error if not done
588 if ( status === 1 ) {
589 done(0, "error", "" + e);
591 // Simply rethrow otherwise
602 // Serialize an array of form elements or a set of
603 // key/values into a query string
604 param: function( a, traditional ) {
606 add = function( key, value ) {
607 // If value is a function, invoke it and return its value
608 value = jQuery.isFunction(value) ? value() : value;
609 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
612 // Set traditional to true for jQuery <= 1.3.2 behavior.
613 if ( traditional === undefined ) {
614 traditional = jQuery.ajaxSettings.traditional;
617 // If an array was passed in, assume that it is an array of form elements.
618 if ( jQuery.isArray(a) || a.jquery ) {
619 // Serialize the form elements
620 jQuery.each( a, function() {
621 add( this.name, this.value );
625 // If traditional, encode the "old" way (the way 1.3.2 or older
626 // did it), otherwise encode params recursively.
627 for ( var prefix in a ) {
628 buildParams( prefix, a[prefix], traditional, add );
632 // Return the resulting serialization
633 return s.join("&").replace(r20, "+");
637 function buildParams( prefix, obj, traditional, add ) {
638 if ( jQuery.isArray(obj) && obj.length ) {
639 // Serialize array item.
640 jQuery.each( obj, function( i, v ) {
641 if ( traditional || rbracket.test( prefix ) ) {
642 // Treat each array item as a scalar.
646 // If array item is non-scalar (array or object), encode its
647 // numeric index to resolve deserialization ambiguity issues.
648 // Note that rack (as of 1.0.0) can't currently deserialize
649 // nested arrays properly, and attempting to do so may cause
650 // a server error. Possible fixes are to modify rack's
651 // deserialization algorithm or to provide an option or flag
652 // to force array serialization to be shallow.
653 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
657 } else if ( !traditional && obj != null && typeof obj === "object" ) {
658 // If we see an array here, it is empty and should be treated as an empty
660 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
663 // Serialize object item.
665 jQuery.each( obj, function( k, v ) {
666 buildParams( prefix + "[" + k + "]", v, traditional, add );
671 // Serialize scalar item.
676 // This is still on the jQuery object... for now
677 // Want to move this to jQuery.ajax some day
680 // Counter for holding the number of active queries
683 // Last-Modified header cache for next request
689 // Base inspection function for prefilters and transports
690 function inspectPrefiltersOrTransports( structure , options , originalOptions , dataType , tested ) {
692 dataType = dataType || options.dataTypes[0];
693 tested = tested || {};
695 if ( ! tested[ dataType ] ) {
697 tested[ dataType ] = true;
699 var list = structure[ dataType ],
701 length = list ? list.length : 0,
702 executeOnly = structure === prefilters,
705 for( ; ( executeOnly || ! selected ) && i < length ; i++ ) {
706 selected = list[ i ]( options , originalOptions );
707 // If we got redirected to a different dataType,
708 // we add it and switch to the corresponding list
709 if ( typeof( selected ) === "string" && selected !== dataType ) {
710 options.dataTypes.unshift( selected );
711 selected = inspectPrefiltersOrTransports(
712 structure , options , originalOptions , selected , tested );
713 // We always break in order not to continue
714 // to iterate in previous list
718 // If we're only executing or nothing was selected
719 // we try the catchall dataType
720 if ( ! tested[ "*" ] && ( executeOnly || ! selected ) ) {
721 selected = inspectPrefiltersOrTransports(
722 structure , options , originalOptions , "*" , tested );
724 // This will be ignored by ajaxPrefilter
725 // so it's safe to return no matter what
730 function addToPrefiltersOrTransports( structure , dataTypeExpression , functor ) {
732 var dataTypes = dataTypeExpression.split( rspacesAjax ),
734 length = dataTypes.length,
739 // For each dataType in the dataTypeExpression
740 for( ; i < length ; i++ ) {
741 dataType = dataTypes[ i ];
742 // We control if we're asked to add before
743 // any existing element
744 placeBefore = /^\+/.test( dataType );
746 dataType = dataType.substr( 1 );
748 list = structure[ dataType ] = structure[ dataType ] || [];
749 // then we add to the structure accordingly
750 list[ placeBefore ? "unshift" : "push" ]( functor );
754 // Base function for both ajaxPrefilter and ajaxTransport
755 function prefiltersOrTransports( structure , arg1 , arg2 , type /* internal */ ) {
757 type = jQuery.type( arg1 );
759 if ( type === "object" ) {
760 // We have an options map so we have to inspect the structure
761 return inspectPrefiltersOrTransports( structure , arg1 , arg2 );
763 // We're requested to add to the structure
764 // Signature is ( dataTypeExpression , function )
765 // with dataTypeExpression being optional and
766 // defaulting to auto ("*")
767 type = ( type === "function" );
772 // We control that the second argument is really a function
773 if ( type || jQuery.isFunction( arg2 ) ) {
774 addToPrefiltersOrTransports( structure , arg1 || "*" , arg2 );
779 // Handles responses to an ajax request:
780 // - sets all responseXXX fields accordingly
781 // - finds the right dataType (mediating between content-type and expecting dataType)
782 // - returns the corresponding response
783 function ajaxHandleResponses( s , jXHR , responses ) {
785 var contents = s.contents,
786 dataTypes = s.dataTypes,
787 responseFields = s.responseFields,
793 // Fill responseXXX fields
794 for( type in responseFields ) {
795 if ( type in responses ) {
796 jXHR[ responseFields[ type ] ] = responses[ type ];
800 // Remove auto dataType and get content-type in the process
801 while( dataTypes[0] === "*" ) {
803 if ( ct === undefined ) {
804 ct = jXHR.getResponseHeader( "content-type" );
808 // Check if we're dealing with a known content-type
810 for ( type in contents ) {
811 if ( contents[ type ] && contents[ type ].test( ct ) ) {
812 dataTypes.unshift( type );
818 // Check to see if we have a response for the expected dataType
819 if ( dataTypes[0] in responses ) {
820 finalDataType = dataTypes[0];
822 // Try convertible dataTypes
823 for ( type in responses ) {
824 if ( ! dataTypes[0] || s.converters[ type + " " + dataTypes[0] ] ) {
825 finalDataType = type;
828 if ( ! firstDataType ) {
829 firstDataType = type;
832 // Or just use first one
833 finalDataType = finalDataType || firstDataType;
836 // If we found a dataType
837 // We add the dataType to the list if needed
838 // and return the corresponding response
839 if ( finalDataType ) {
840 if ( finalDataType !== dataTypes[0] ) {
841 dataTypes.unshift( finalDataType );
843 return responses[ finalDataType ];
847 // Chain conversions given the request and the original response
848 function ajaxConvert( s , response ) {
850 // Apply the dataFilter if provided
851 if ( s.dataFilter ) {
852 response = s.dataFilter( response , s.dataType );
855 var dataTypes = s.dataTypes,
856 converters = s.converters,
858 length = dataTypes.length,
860 // Current and previous dataTypes
861 current = dataTypes[0],
863 // Conversion expression
865 // Conversion function
867 // Conversion functions (when text is used in-between)
871 // For each dataType in the chain
872 for( i = 1 ; i < length ; i++ ) {
876 current = dataTypes[ i ];
878 // If current is auto dataType, update it to prev
879 if( current === "*" ) {
881 // If no auto and dataTypes are actually different
882 } else if ( prev !== "*" && prev !== current ) {
885 conversion = prev + " " + current;
886 conv = converters[ conversion ] || converters[ "* " + current ];
888 // If there is no direct converter, search transitively
891 for( conv1 in converters ) {
892 tmp = conv1.split( " " );
893 if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
894 conv2 = converters[ tmp[ 1 ] + " " + current ];
896 conv1 = converters[ conv1 ];
897 if ( conv1 === true ) {
899 } else if ( conv2 === true ) {
907 // If we found no converter, dispatch an error
908 if ( ! ( conv || conv2 ) ) {
909 jQuery.error( "No conversion from " + conversion.replace( " " , " to " ) );
911 // If found converter is not an equivalence
912 if ( conv !== true ) {
913 // Convert with 1 or 2 converters accordingly
914 response = conv ? conv( response ) : conv2( conv1( response ) );