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 );
164 if ( settings.context ) {
165 jQuery.ajaxSettings.context = settings.context;
173 contentType: "application/x-www-form-urlencoded",
189 xml: "application/xml, text/xml",
192 json: "application/json, text/javascript",
203 // 1) They are useful to introduce custom dataTypes (see transport/jsonp for an example)
204 // 2) These are called:
205 // * BEFORE asking for a transport
206 // * AFTER param serialization (s.data is a string if s.processData is true)
207 // 3) key is the dataType
208 // 4) the catchall symbol "*" can be used
209 // 5) execution will start with transport dataType and THEN continue down to "*" if needed
212 // Transports bindings
213 // 1) key is the dataType
214 // 2) the catchall symbol "*" can be used
215 // 3) selection will start with transport dataType and THEN go to "*" if needed
218 // List of data converters
219 // 1) key format is "source_type destination_type" (a single space in-between)
220 // 2) the catchall symbol "*" can be used for source_type
223 // Convert anything to text
224 "* text": window.String,
226 // Text to html (true = no transformation)
229 // Evaluate text as a json expression
230 "text json": jQuery.parseJSON,
233 "text xml": jQuery.parseXML
236 // Utility function that handles dataType when response is received
237 // (for those transports that can give text or xml responses)
238 determineDataType: function( ct , text , xml ) {
241 contents = s.contents,
244 dataTypes = s.dataTypes,
245 transportDataType = dataTypes[0],
248 // Auto (xml, json, script or text determined given headers)
249 if ( transportDataType === "*" ) {
251 for ( type in contents ) {
252 if ( ( regexp = contents[ type ] ) && regexp.test( ct ) ) {
253 transportDataType = dataTypes[0] = type;
259 // xml and parsed as such
260 if ( transportDataType === "xml" &&
262 xml.documentElement /* #4958 */ ) {
266 // Text response was provided
271 // If it's not really text, defer to converters
272 if ( transportDataType !== "text" ) {
273 dataTypes.unshift( "text" );
283 ajaxPrefilter: function( a , b ) {
284 ajaxPrefilterOrTransport( "prefilters" , a , b );
287 ajaxTransport: function( a , b ) {
288 return ajaxPrefilterOrTransport( "transports" , a , b );
292 ajax: function( url , options ) {
295 if ( arguments.length === 1 ) {
297 url = options ? options.url : undefined;
300 // Force options to be an object
301 options = options || {};
303 // Get the url if provided separately
304 options.url = url || options.url;
306 var // Create the final options object
307 s = jQuery.extend( true , {} , jQuery.ajaxSettings , options ),
309 jQuery_lastModified = jQuery.lastModified,
310 jQuery_etag = jQuery.etag,
311 // Callbacks contexts
312 // We force the original context if it exists
313 // or take it from jQuery.ajaxSettings otherwise
314 // (plain objects used as context get extended)
316 ( s.context = ( "context" in options ? options : jQuery.ajaxSettings ).context ) || s,
317 globalEventContext = callbackContext === s ? jQuery.event : jQuery( callbackContext ),
319 deferred = jQuery.Deferred(),
320 completeDeferred = jQuery._Deferred(),
321 // Status-dependent callbacks
322 statusCode = s.statusCode || {},
323 // Headers (they are sent all at once)
326 responseHeadersString,
332 // Cross-domain detection vars
333 loc = document.location,
334 protocol = loc.protocol || "http:",
346 setRequestHeader: function(name,value) {
348 requestHeaders[ name.toLowerCase() ] = value;
354 getAllResponseHeaders: function() {
355 return state === 2 ? responseHeadersString : null;
358 // Builds headers hashtable if needed
359 getResponseHeader: function( key ) {
365 if ( !responseHeaders ) {
367 responseHeaders = {};
369 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
370 responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
373 match = responseHeaders[ key.toLowerCase() ];
377 return match || null;
380 // Cancel the request
381 abort: function( statusText ) {
383 transport.abort( statusText || "abort" );
385 done( 0 , statusText );
390 // Callback for when everything is done
391 // It is defined here because jslint complains if it is declared
392 // at the end of the function (which would be more logical and readable)
393 function done( status , statusText , response , headers) {
400 // State is "done" now
403 // Dereference transport for early garbage collection
404 // (no matter how long the jXHR transport will be used
405 transport = undefined;
408 jXHR.readyState = status ? 4 : 0;
410 // Cache response headers
411 responseHeadersString = headers || "";
413 // Clear timeout if it exists
414 if ( timeoutTimer ) {
415 clearTimeout(timeoutTimer);
420 // and ifModified status
421 ifModified = s.ifModified,
430 // To keep track of statusCode based callbacks
433 // If successful, handle type chaining
434 if ( status >= 200 && status < 300 || status === 304 ) {
436 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
437 if ( s.ifModified ) {
439 var lastModified = jXHR.getResponseHeader("Last-Modified"),
440 etag = jXHR.getResponseHeader("Etag");
443 jQuery_lastModified[ s.url ] = lastModified;
446 jQuery_etag[ s.url ] = etag;
451 if ( status === 304 ) {
453 // Set the statusText accordingly
454 statusText = "notmodified";
461 // Set the statusText accordingly
462 statusText = "success";
464 // Chain data conversions and determine the final value
465 // (if an exception is thrown in the process, it'll be notified as an error)
473 // Conversion expression
475 // Conversion function
477 // Conversion functions (when text is used in-between)
480 // Local references to dataTypes & converters
481 dataTypes = s.dataTypes,
482 converters = s.converters,
483 // DataType to responseXXX field mapping
489 // For each dataType in the chain
490 for( i = 0 ; i < dataTypes.length ; i++ ) {
492 current = dataTypes[ i ];
494 // If a responseXXX field for this dataType exists
495 // and if it hasn't been set yet
496 if ( responses[ current ] ) {
498 jXHR[ "response" + responses[ current ] ] = response;
500 responses[ current ] = 0;
503 // If this is not the first element
506 // Get the dataType to convert from
507 prev = dataTypes[ i - 1 ];
509 // If no catch-all and dataTypes are actually different
510 if ( prev !== "*" && current !== "*" && prev !== current ) {
513 conversion = prev + " " + current;
514 conv = converters[ conversion ] || converters[ "* " + current ];
518 // If there is no direct converter and none of the dataTypes is text
519 if ( ! conv && prev !== "text" && current !== "text" ) {
520 // Try with text in-between
521 conv1 = converters[ prev + " text" ] || converters[ "* text" ];
522 conv2 = converters[ "text " + current ];
523 // Revert back to a single converter
524 // if one of the converter is an equivalence
525 if ( conv1 === true ) {
527 } else if ( conv2 === true ) {
531 // If we found no converter, dispatch an error
532 if ( ! ( conv || conv1 && conv2 ) ) {
535 // If found converter is not an equivalence
536 if ( conv !== true ) {
537 // Convert with 1 or 2 converters accordingly
538 response = conv ? conv( response ) : conv2( conv1( response ) );
541 // If it is the first element of the chain
542 // and we have a dataFilter
543 } else if ( s.dataFilter ) {
544 // Apply the dataFilter
545 response = s.dataFilter( response , current );
546 // Get dataTypes again in case the filter changed them
547 dataTypes = s.dataTypes;
552 // We have a real success
556 // If an exception was thrown
559 // We have a parsererror
560 statusText = "parsererror";
566 // if not success, mark it as an error
569 error = statusText = statusText || "error";
571 // Set responseText if needed
573 jXHR.responseText = response;
577 // Set data for the fake xhr object
578 jXHR.status = status;
579 jXHR.statusText = statusText;
583 deferred.fire( callbackContext , [ success , statusText , jXHR ] );
585 deferred.fireReject( callbackContext , [ jXHR , statusText , error ] );
588 // Status-dependent callbacks
589 oldStatusCode = statusCode;
590 statusCode = undefined;
591 jXHR.statusCode( oldStatusCode );
594 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ) ,
595 [ jXHR , s , isSuccess ? success : error ] );
599 completeDeferred.fire( callbackContext, [ jXHR , statusText ] );
602 globalEventContext.trigger( "ajaxComplete" , [ jXHR , s] );
603 // Handle the global AJAX counter
604 if ( ! --jQuery.active ) {
605 jQuery.event.trigger( "ajaxStop" );
611 deferred.promise( jXHR );
612 jXHR.success = jXHR.done;
613 jXHR.error = jXHR.fail;
614 jXHR.complete = completeDeferred.done;
616 // Status-dependent callbacks
617 jXHR.statusCode = function( map ) {
622 statusCode[ tmp ] = [ statusCode[ tmp ] , map[ tmp ] ];
625 tmp = map[ jXHR.status ];
626 jXHR.done( tmp ).fail( tmp );
632 // Remove hash character (#7531: and string promotion)
633 s.url = ( "" + s.url ).replace( rhash , "" );
635 // Extract dataTypes list
636 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( /\s+/ );
638 // Determine if a cross-domain request is in order
639 if ( ! s.crossDomain ) {
640 parts = rurl.exec( s.url.toLowerCase() );
643 ( parts[ 1 ] && parts[ 1 ] != protocol ||
644 parts[ 2 ] != loc.hostname ||
645 ( parts[ 3 ] || ( ( parts[ 1 ] || protocol ) === "http:" ? 80 : 443 ) ) !=
646 ( loc.port || ( protocol === "http:" ? 80 : 443 ) ) )
650 // Convert data if not already a string
651 if ( s.data && s.processData && typeof s.data !== "string" ) {
652 s.data = jQuery.param( s.data , s.traditional );
656 jQuery.ajaxPrefilter( s , options );
658 // Uppercase the type
659 s.type = s.type.toUpperCase();
661 // Determine if request has content
662 s.hasContent = ! rnoContent.test( s.type );
664 // Watch for a new set of requests
665 if ( s.global && jQuery.active++ === 0 ) {
666 jQuery.event.trigger( "ajaxStart" );
669 // More options handling for requests with no content
670 if ( ! s.hasContent ) {
672 // If data is available, append data to url
674 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
677 // Add anti-cache in url if needed
678 if ( s.cache === false ) {
680 var ts = jQuery.now(),
681 // try replacing _= if it is there
682 ret = s.url.replace( rts , "$1_=" + ts );
684 // if nothing was replaced, add timestamp to the end
685 s.url = ret + ( (ret == s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "");
689 // Set the correct header, if data is being sent
690 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
691 requestHeaders[ "content-type" ] = s.contentType;
694 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
695 if ( s.ifModified ) {
696 if ( jQuery_lastModified[ s.url ] ) {
697 requestHeaders[ "if-modified-since" ] = jQuery_lastModified[ s.url ];
699 if ( jQuery_etag[ s.url ] ) {
700 requestHeaders[ "if-none-match" ] = jQuery_etag[ s.url ];
704 // Set the Accepts header for the server, depending on the dataType
705 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
706 s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
709 // Check for headers option
710 for ( i in s.headers ) {
711 requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
714 // Allow custom headers/mimetypes and early abort
715 if ( s.beforeSend && ( s.beforeSend.call( callbackContext , jXHR , s ) === false || state === 2 ) ) {
717 // Abort if not done already
725 // Install callbacks on deferreds
726 for ( i in { success:1, error:1, complete:1 } ) {
731 transport = jQuery.ajaxTransport( s , options );
733 // If no transport, we auto-abort
736 done( 0 , "notransport" );
740 // Set state as sending
741 state = jXHR.readyState = 1;
745 globalEventContext.trigger( "ajaxSend" , [ jXHR , s ] );
749 if ( s.async && s.timeout > 0 ) {
750 timeoutTimer = setTimeout(function(){
751 jXHR.abort( "timeout" );
757 transport.send(requestHeaders, done);
759 // Propagate exception as error if not done
760 if ( status === 1 ) {
762 done(0, "error", "" + e);
765 // Simply rethrow otherwise
776 // Serialize an array of form elements or a set of
777 // key/values into a query string
778 param: function( a, traditional ) {
780 add = function( key, value ) {
781 // If value is a function, invoke it and return its value
782 value = jQuery.isFunction(value) ? value() : value;
783 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
786 // Set traditional to true for jQuery <= 1.3.2 behavior.
787 if ( traditional === undefined ) {
788 traditional = jQuery.ajaxSettings.traditional;
791 // If an array was passed in, assume that it is an array of form elements.
792 if ( jQuery.isArray(a) || a.jquery ) {
793 // Serialize the form elements
794 jQuery.each( a, function() {
795 add( this.name, this.value );
799 // If traditional, encode the "old" way (the way 1.3.2 or older
800 // did it), otherwise encode params recursively.
801 for ( var prefix in a ) {
802 buildParams( prefix, a[prefix], traditional, add );
806 // Return the resulting serialization
807 return s.join("&").replace(r20, "+");
811 function buildParams( prefix, obj, traditional, add ) {
812 if ( jQuery.isArray(obj) && obj.length ) {
813 // Serialize array item.
814 jQuery.each( obj, function( i, v ) {
815 if ( traditional || rbracket.test( prefix ) ) {
816 // Treat each array item as a scalar.
820 // If array item is non-scalar (array or object), encode its
821 // numeric index to resolve deserialization ambiguity issues.
822 // Note that rack (as of 1.0.0) can't currently deserialize
823 // nested arrays properly, and attempting to do so may cause
824 // a server error. Possible fixes are to modify rack's
825 // deserialization algorithm or to provide an option or flag
826 // to force array serialization to be shallow.
827 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
831 } else if ( !traditional && obj != null && typeof obj === "object" ) {
832 // If we see an array here, it is empty and should be treated as an empty
834 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
837 // Serialize object item.
839 jQuery.each( obj, function( k, v ) {
840 buildParams( prefix + "[" + k + "]", v, traditional, add );
845 // Serialize scalar item.
850 // This is still on the jQuery object... for now
851 // Want to move this to jQuery.ajax some day
854 // Counter for holding the number of active queries
857 // Last-Modified header cache for next request
863 // Base function for both ajaxPrefilter and ajaxTransport
864 function ajaxPrefilterOrTransport( arg0 , arg1 , arg2 ) {
866 var type = jQuery.type( arg1 ),
867 structure = jQuery.ajaxSettings[ arg0 ],
871 // We have an options map so we have to inspect the structure
872 if ( type === "object" ) {
875 originalOptions = arg2,
876 // When dealing with prefilters, we execute only
877 // (no selection so we never stop when a function
878 // returns a non-falsy, non-string value)
879 executeOnly = ( arg0 === "prefilters" ),
880 inspect = function( dataType, tested ) {
882 if ( ! tested[ dataType ] ) {
884 tested[ dataType ] = true;
886 var list = structure[ dataType ],
889 for( i = 0, length = list ? list.length : 0 ; ( executeOnly || ! selected ) && i < length ; i++ ) {
890 selected = list[ i ]( options , originalOptions );
891 // If we got redirected to a different dataType,
892 // we add it and switch to the corresponding list
893 if ( typeof( selected ) === "string" && selected !== dataType ) {
894 options.dataTypes.unshift( selected );
895 selected = inspect( selected , tested );
896 // We always break in order not to continue
897 // to iterate in previous list
901 // If we're only executing or nothing was selected
902 // we try the catchall dataType
903 if ( executeOnly || ! selected ) {
904 selected = inspect( "*" , tested );
906 // This will be ignored by ajaxPrefilter
907 // so it's safe to return no matter what
913 // Start inspection with current transport dataType
914 return inspect( options.dataTypes[ 0 ] , {} );
918 // We're requested to add to the structure
919 // Signature is ( dataTypeExpression , function )
920 // with dataTypeExpression being optional and
921 // defaulting to catchAll (*)
922 type = type === "function";
930 // We control that the second argument is really a function
931 if ( type || jQuery.isFunction( arg2 ) ) {
933 var dataTypes = arg1.split( /\s+/ ),
939 // For each dataType in the dataTypeExpression
940 for( i = 0 , length = dataTypes.length ; i < length ; i++ ) {
941 dataType = dataTypes[ i ];
942 // We control if we're asked to add before
943 // any existing element
944 placeBefore = /^\+/.test( dataType );
946 dataType = dataType.substr( 1 );
948 list = structure[ dataType ] = structure[ dataType ] || [];
949 // then we add to the structure accordingly
950 list[ placeBefore ? "unshift" : "push" ]( functor );