Fixes #8095. Properly handles the case where browser cache needs to be bypassed while...
[jquery.git] / src / ajax.js
1 (function( jQuery ) {
2
3 var r20 = /%20/g,
4         rbracket = /\[\]$/,
5         rCRLF = /\r?\n/g,
6         rhash = /#.*$/,
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)$/,
10         rprotocol = /^\/\//,
11         rquery = /\?/,
12         rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
13         rselectTextarea = /^(?:select|textarea)/i,
14         rspacesAjax = /\s+/,
15         rts = /([?&])_=[^&]*/,
16         rurl = /^(\w+:)\/\/([^\/?#:]+)(?::(\d+))?/,
17
18         // Keep a copy of the old load method
19         _load = jQuery.fn.load,
20
21         /* Prefilters
22          * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
23          * 2) These are called:
24          *    - BEFORE asking for a transport
25          *    - AFTER param serialization (s.data is a string if s.processData is true)
26          * 3) key is the dataType
27          * 4) the catchall symbol "*" can be used
28          * 5) execution will start with transport dataType and THEN continue down to "*" if needed
29          */
30         prefilters = {},
31
32         /* Transports bindings
33          * 1) key is the dataType
34          * 2) the catchall symbol "*" can be used
35          * 3) selection will start with transport dataType and THEN go to "*" if needed
36          */
37         transports = {};
38
39 // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
40 function addToPrefiltersOrTransports( structure ) {
41
42         // dataTypeExpression is optional and defaults to "*"
43         return function( dataTypeExpression, func ) {
44
45                 if ( typeof dataTypeExpression !== "string" ) {
46                         func = dataTypeExpression;
47                         dataTypeExpression = "*";
48                 }
49
50                 if ( jQuery.isFunction( func ) ) {
51                         var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
52                                 i = 0,
53                                 length = dataTypes.length,
54                                 dataType,
55                                 list,
56                                 placeBefore;
57
58                         // For each dataType in the dataTypeExpression
59                         for(; i < length; i++ ) {
60                                 dataType = dataTypes[ i ];
61                                 // We control if we're asked to add before
62                                 // any existing element
63                                 placeBefore = /^\+/.test( dataType );
64                                 if ( placeBefore ) {
65                                         dataType = dataType.substr( 1 ) || "*";
66                                 }
67                                 list = structure[ dataType ] = structure[ dataType ] || [];
68                                 // then we add to the structure accordingly
69                                 list[ placeBefore ? "unshift" : "push" ]( func );
70                         }
71                 }
72         };
73 }
74
75 //Base inspection function for prefilters and transports
76 function inspectPrefiltersOrTransports( structure, options, originalOptions, jXHR,
77                 dataType /* internal */, inspected /* internal */ ) {
78
79         dataType = dataType || options.dataTypes[ 0 ];
80         inspected = inspected || {};
81
82         inspected[ dataType ] = true;
83
84         var list = structure[ dataType ],
85                 i = 0,
86                 length = list ? list.length : 0,
87                 executeOnly = ( structure === prefilters ),
88                 selection;
89
90         for(; i < length && ( executeOnly || !selection ); i++ ) {
91                 selection = list[ i ]( options, originalOptions, jXHR );
92                 // If we got redirected to another dataType
93                 // we try there if not done already
94                 if ( typeof selection === "string" ) {
95                         if ( inspected[ selection ] ) {
96                                 selection = undefined;
97                         } else {
98                                 options.dataTypes.unshift( selection );
99                                 selection = inspectPrefiltersOrTransports(
100                                                 structure, options, originalOptions, jXHR, selection, inspected );
101                         }
102                 }
103         }
104         // If we're only executing or nothing was selected
105         // we try the catchall dataType if not done already
106         if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
107                 selection = inspectPrefiltersOrTransports(
108                                 structure, options, originalOptions, jXHR, "*", inspected );
109         }
110         // unnecessary when only executing (prefilters)
111         // but it'll be ignored by the caller in that case
112         return selection;
113 }
114
115 jQuery.fn.extend({
116         load: function( url, params, callback ) {
117                 if ( typeof url !== "string" && _load ) {
118                         return _load.apply( this, arguments );
119
120                 // Don't do a request if no elements are being requested
121                 } else if ( !this.length ) {
122                         return this;
123                 }
124
125                 var off = url.indexOf( " " );
126                 if ( off >= 0 ) {
127                         var selector = url.slice( off, url.length );
128                         url = url.slice( 0, off );
129                 }
130
131                 // Default to a GET request
132                 var type = "GET";
133
134                 // If the second parameter was provided
135                 if ( params ) {
136                         // If it's a function
137                         if ( jQuery.isFunction( params ) ) {
138                                 // We assume that it's the callback
139                                 callback = params;
140                                 params = null;
141
142                         // Otherwise, build a param string
143                         } else if ( typeof params === "object" ) {
144                                 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
145                                 type = "POST";
146                         }
147                 }
148
149                 var self = this;
150
151                 // Request the remote document
152                 jQuery.ajax({
153                         url: url,
154                         type: type,
155                         dataType: "html",
156                         data: params,
157                         // Complete callback (responseText is used internally)
158                         complete: function( jXHR, status, responseText ) {
159                                 // Store the response as specified by the jXHR object
160                                 responseText = jXHR.responseText;
161                                 // If successful, inject the HTML into all the matched elements
162                                 if ( jXHR.isResolved() ) {
163                                         // #4825: Get the actual response in case
164                                         // a dataFilter is present in ajaxSettings
165                                         jXHR.done(function( r ) {
166                                                 responseText = r;
167                                         });
168                                         // See if a selector was specified
169                                         self.html( selector ?
170                                                 // Create a dummy div to hold the results
171                                                 jQuery("<div>")
172                                                         // inject the contents of the document in, removing the scripts
173                                                         // to avoid any 'Permission Denied' errors in IE
174                                                         .append(responseText.replace(rscript, ""))
175
176                                                         // Locate the specified elements
177                                                         .find(selector) :
178
179                                                 // If not, just inject the full result
180                                                 responseText );
181                                 }
182
183                                 if ( callback ) {
184                                         self.each( callback, [ responseText, status, jXHR ] );
185                                 }
186                         }
187                 });
188
189                 return this;
190         },
191
192         serialize: function() {
193                 return jQuery.param( this.serializeArray() );
194         },
195
196         serializeArray: function() {
197                 return this.map(function(){
198                         return this.elements ? jQuery.makeArray( this.elements ) : this;
199                 })
200                 .filter(function(){
201                         return this.name && !this.disabled &&
202                                 ( this.checked || rselectTextarea.test( this.nodeName ) ||
203                                         rinput.test( this.type ) );
204                 })
205                 .map(function( i, elem ){
206                         var val = jQuery( this ).val();
207
208                         return val == null ?
209                                 null :
210                                 jQuery.isArray( val ) ?
211                                         jQuery.map( val, function( val, i ){
212                                                 return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
213                                         }) :
214                                         { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
215                 }).get();
216         }
217 });
218
219 // Attach a bunch of functions for handling common AJAX events
220 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
221         jQuery.fn[ o ] = function( f ){
222                 return this.bind( o, f );
223         };
224 } );
225
226 jQuery.each( [ "get", "post" ], function( i, method ) {
227         jQuery[ method ] = function( url, data, callback, type ) {
228                 // shift arguments if data argument was omitted
229                 if ( jQuery.isFunction( data ) ) {
230                         type = type || callback;
231                         callback = data;
232                         data = null;
233                 }
234
235                 return jQuery.ajax({
236                         type: method,
237                         url: url,
238                         data: data,
239                         success: callback,
240                         dataType: type
241                 });
242         };
243 } );
244
245 jQuery.extend({
246
247         getScript: function( url, callback ) {
248                 return jQuery.get( url, null, callback, "script" );
249         },
250
251         getJSON: function( url, data, callback ) {
252                 return jQuery.get( url, data, callback, "json" );
253         },
254
255         ajaxSetup: function( settings ) {
256                 jQuery.extend( true, jQuery.ajaxSettings, settings );
257                 if ( settings.context ) {
258                         jQuery.ajaxSettings.context = settings.context;
259                 }
260         },
261
262         ajaxSettings: {
263                 url: location.href,
264                 global: true,
265                 type: "GET",
266                 contentType: "application/x-www-form-urlencoded",
267                 processData: true,
268                 async: true,
269                 /*
270                 timeout: 0,
271                 data: null,
272                 dataType: null,
273                 username: null,
274                 password: null,
275                 cache: null,
276                 traditional: false,
277                 headers: {},
278                 crossDomain: null,
279                 */
280
281                 accepts: {
282                         xml: "application/xml, text/xml",
283                         html: "text/html",
284                         text: "text/plain",
285                         json: "application/json, text/javascript",
286                         "*": "*/*"
287                 },
288
289                 contents: {
290                         xml: /xml/,
291                         html: /html/,
292                         json: /json/
293                 },
294
295                 responseFields: {
296                         xml: "responseXML",
297                         text: "responseText"
298                 },
299
300                 // List of data converters
301                 // 1) key format is "source_type destination_type" (a single space in-between)
302                 // 2) the catchall symbol "*" can be used for source_type
303                 converters: {
304
305                         // Convert anything to text
306                         "* text": window.String,
307
308                         // Text to html (true = no transformation)
309                         "text html": true,
310
311                         // Evaluate text as a json expression
312                         "text json": jQuery.parseJSON,
313
314                         // Parse text as xml
315                         "text xml": jQuery.parseXML
316                 }
317         },
318
319         ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
320         ajaxTransport: addToPrefiltersOrTransports( transports ),
321
322         // Main method
323         ajax: function( url, options ) {
324
325                 // If options is not an object,
326                 // we simulate pre-1.5 signature
327                 if ( typeof options !== "object" ) {
328                         options = url;
329                         url = undefined;
330                 }
331
332                 // Force options to be an object
333                 options = options || {};
334
335                 var // Create the final options object
336                         s = jQuery.extend( true, {}, jQuery.ajaxSettings, options ),
337                         // Callbacks context
338                         // We force the original context if it exists
339                         // or take it from jQuery.ajaxSettings otherwise
340                         // (plain objects used as context get extended)
341                         callbackContext =
342                                 ( s.context = ( "context" in options ? options : jQuery.ajaxSettings ).context ) || s,
343                         // Context for global events
344                         // It's the callbackContext if one was provided in the options
345                         // and if it's a DOM node
346                         globalEventContext = callbackContext !== s && callbackContext.nodeType ?
347                                 jQuery( callbackContext ) : jQuery.event,
348                         // Deferreds
349                         deferred = jQuery.Deferred(),
350                         completeDeferred = jQuery._Deferred(),
351                         // Status-dependent callbacks
352                         statusCode = s.statusCode || {},
353                         // ifModified key
354                         ifModifiedKey,
355                         // Headers (they are sent all at once)
356                         requestHeaders = {},
357                         // Response headers
358                         responseHeadersString,
359                         responseHeaders,
360                         // transport
361                         transport,
362                         // timeout handle
363                         timeoutTimer,
364                         // Cross-domain detection vars
365                         loc = document.location,
366                         protocol = loc.protocol || "http:",
367                         parts,
368                         // The jXHR state
369                         state = 0,
370                         // Loop variable
371                         i,
372                         // Fake xhr
373                         jXHR = {
374
375                                 readyState: 0,
376
377                                 // Caches the header
378                                 setRequestHeader: function( name, value ) {
379                                         if ( state === 0 ) {
380                                                 requestHeaders[ name.toLowerCase() ] = value;
381                                         }
382                                         return this;
383                                 },
384
385                                 // Raw string
386                                 getAllResponseHeaders: function() {
387                                         return state === 2 ? responseHeadersString : null;
388                                 },
389
390                                 // Builds headers hashtable if needed
391                                 getResponseHeader: function( key ) {
392                                         var match;
393                                         if ( state === 2 ) {
394                                                 if ( !responseHeaders ) {
395                                                         responseHeaders = {};
396                                                         while( ( match = rheaders.exec( responseHeadersString ) ) ) {
397                                                                 responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
398                                                         }
399                                                 }
400                                                 match = responseHeaders[ key.toLowerCase() ];
401                                         }
402                                         return match || null;
403                                 },
404
405                                 // Cancel the request
406                                 abort: function( statusText ) {
407                                         statusText = statusText || "abort";
408                                         if ( transport ) {
409                                                 transport.abort( statusText );
410                                         }
411                                         done( 0, statusText );
412                                         return this;
413                                 }
414                         };
415
416                 // Callback for when everything is done
417                 // It is defined here because jslint complains if it is declared
418                 // at the end of the function (which would be more logical and readable)
419                 function done( status, statusText, responses, headers) {
420
421                         // Called once
422                         if ( state === 2 ) {
423                                 return;
424                         }
425
426                         // State is "done" now
427                         state = 2;
428
429                         // Clear timeout if it exists
430                         if ( timeoutTimer ) {
431                                 clearTimeout( timeoutTimer );
432                         }
433
434                         // Dereference transport for early garbage collection
435                         // (no matter how long the jXHR object will be used)
436                         transport = undefined;
437
438                         // Cache response headers
439                         responseHeadersString = headers || "";
440
441                         // Set readyState
442                         jXHR.readyState = status ? 4 : 0;
443
444                         var isSuccess,
445                                 success,
446                                 error,
447                                 response = responses ? ajaxHandleResponses( s, jXHR, responses ) : undefined,
448                                 lastModified,
449                                 etag;
450
451                         // If successful, handle type chaining
452                         if ( status >= 200 && status < 300 || status === 304 ) {
453
454                                 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
455                                 if ( s.ifModified ) {
456
457                                         if ( ( lastModified = jXHR.getResponseHeader( "Last-Modified" ) ) ) {
458                                                 jQuery.lastModified[ ifModifiedKey ] = lastModified;
459                                         }
460                                         if ( ( etag = jXHR.getResponseHeader( "Etag" ) ) ) {
461                                                 jQuery.etag[ ifModifiedKey ] = etag;
462                                         }
463                                 }
464
465                                 // If not modified
466                                 if ( status === 304 ) {
467
468                                         statusText = "notmodified";
469                                         isSuccess = true;
470
471                                 // If we have data
472                                 } else {
473
474                                         try {
475                                                 success = ajaxConvert( s, response );
476                                                 statusText = "success";
477                                                 isSuccess = true;
478                                         } catch(e) {
479                                                 // We have a parsererror
480                                                 statusText = "parsererror";
481                                                 error = e;
482                                         }
483                                 }
484                         } else {
485                                 // We extract error from statusText
486                                 // then normalize statusText and status for non-aborts
487                                 error = statusText;
488                                 if( status ) {
489                                         statusText = "error";
490                                         if ( status < 0 ) {
491                                                 status = 0;
492                                         }
493                                 }
494                         }
495
496                         // Set data for the fake xhr object
497                         jXHR.status = status;
498                         jXHR.statusText = statusText;
499
500                         // Success/Error
501                         if ( isSuccess ) {
502                                 deferred.resolveWith( callbackContext, [ success, statusText, jXHR ] );
503                         } else {
504                                 deferred.rejectWith( callbackContext, [ jXHR, statusText, error ] );
505                         }
506
507                         // Status-dependent callbacks
508                         jXHR.statusCode( statusCode );
509                         statusCode = undefined;
510
511                         if ( s.global ) {
512                                 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
513                                                 [ jXHR, s, isSuccess ? success : error ] );
514                         }
515
516                         // Complete
517                         completeDeferred.resolveWith( callbackContext, [ jXHR, statusText ] );
518
519                         if ( s.global ) {
520                                 globalEventContext.trigger( "ajaxComplete", [ jXHR, s] );
521                                 // Handle the global AJAX counter
522                                 if ( !( --jQuery.active ) ) {
523                                         jQuery.event.trigger( "ajaxStop" );
524                                 }
525                         }
526                 }
527
528                 // Attach deferreds
529                 deferred.promise( jXHR );
530                 jXHR.success = jXHR.done;
531                 jXHR.error = jXHR.fail;
532                 jXHR.complete = completeDeferred.done;
533
534                 // Status-dependent callbacks
535                 jXHR.statusCode = function( map ) {
536                         if ( map ) {
537                                 var tmp;
538                                 if ( state < 2 ) {
539                                         for( tmp in map ) {
540                                                 statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
541                                         }
542                                 } else {
543                                         tmp = map[ jXHR.status ];
544                                         jXHR.then( tmp, tmp );
545                                 }
546                         }
547                         return this;
548                 };
549
550                 // Remove hash character (#7531: and string promotion)
551                 // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
552                 // We also use the url parameter if available
553                 s.url = ( "" + ( url || s.url ) ).replace( rhash, "" ).replace( rprotocol, protocol + "//" );
554
555                 // Extract dataTypes list
556                 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
557
558                 // Determine if a cross-domain request is in order
559                 if ( !s.crossDomain ) {
560                         parts = rurl.exec( s.url.toLowerCase() );
561                         s.crossDomain = !!( parts &&
562                                 ( parts[ 1 ] != protocol || parts[ 2 ] != loc.hostname ||
563                                         ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
564                                                 ( loc.port || ( protocol === "http:" ? 80 : 443 ) ) )
565                         );
566                 }
567
568                 // Convert data if not already a string
569                 if ( s.data && s.processData && typeof s.data !== "string" ) {
570                         s.data = jQuery.param( s.data, s.traditional );
571                 }
572
573                 // Apply prefilters
574                 inspectPrefiltersOrTransports( prefilters, s, options, jXHR );
575
576                 // Uppercase the type
577                 s.type = s.type.toUpperCase();
578
579                 // Determine if request has content
580                 s.hasContent = !rnoContent.test( s.type );
581
582                 // Watch for a new set of requests
583                 if ( s.global && jQuery.active++ === 0 ) {
584                         jQuery.event.trigger( "ajaxStart" );
585                 }
586
587                 // More options handling for requests with no content
588                 if ( !s.hasContent ) {
589
590                         // If data is available, append data to url
591                         if ( s.data ) {
592                                 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
593                         }
594
595                         // Get ifModifiedKey before adding the anti-cache parameter
596                         ifModifiedKey = s.url;
597
598                         // Add anti-cache in url if needed
599                         if ( s.cache === false ) {
600
601                                 var ts = jQuery.now(),
602                                         // try replacing _= if it is there
603                                         ret = s.url.replace( rts, "$1_=" + ts );
604
605                                 // if nothing was replaced, add timestamp to the end
606                                 s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
607                         }
608                 }
609
610                 // Set the correct header, if data is being sent
611                 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
612                         requestHeaders[ "content-type" ] = s.contentType;
613                 }
614
615                 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
616                 if ( s.ifModified ) {
617                         ifModifiedKey = ifModifiedKey || s.url;
618                         if ( jQuery.lastModified[ ifModifiedKey ] ) {
619                                 requestHeaders[ "if-modified-since" ] = jQuery.lastModified[ ifModifiedKey ];
620                         }
621                         if ( jQuery.etag[ ifModifiedKey ] ) {
622                                 requestHeaders[ "if-none-match" ] = jQuery.etag[ ifModifiedKey ];
623                         }
624                 }
625
626                 // Set the Accepts header for the server, depending on the dataType
627                 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
628                         s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
629                         s.accepts[ "*" ];
630
631                 // Check for headers option
632                 for ( i in s.headers ) {
633                         requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
634                 }
635
636                 // Allow custom headers/mimetypes and early abort
637                 if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jXHR, s ) === false || state === 2 ) ) {
638                                 // Abort if not done already
639                                 done( 0, "abort" );
640                                 // Return false
641                                 jXHR = false;
642
643                 } else {
644
645                         // Install callbacks on deferreds
646                         for ( i in { success: 1, error: 1, complete: 1 } ) {
647                                 jXHR[ i ]( s[ i ] );
648                         }
649
650                         // Get transport
651                         transport = inspectPrefiltersOrTransports( transports, s, options, jXHR );
652
653                         // If no transport, we auto-abort
654                         if ( !transport ) {
655                                 done( -1, "No Transport" );
656                         } else {
657                                 // Set state as sending
658                                 state = jXHR.readyState = 1;
659                                 // Send global event
660                                 if ( s.global ) {
661                                         globalEventContext.trigger( "ajaxSend", [ jXHR, s ] );
662                                 }
663                                 // Timeout
664                                 if ( s.async && s.timeout > 0 ) {
665                                         timeoutTimer = setTimeout( function(){
666                                                 jXHR.abort( "timeout" );
667                                         }, s.timeout );
668                                 }
669
670                                 try {
671                                         transport.send( requestHeaders, done );
672                                 } catch (e) {
673                                         // Propagate exception as error if not done
674                                         if ( status < 2 ) {
675                                                 done( -1, e );
676                                         // Simply rethrow otherwise
677                                         } else {
678                                                 jQuery.error( e );
679                                         }
680                                 }
681                         }
682                 }
683                 return jXHR;
684         },
685
686         // Serialize an array of form elements or a set of
687         // key/values into a query string
688         param: function( a, traditional ) {
689                 var s = [],
690                         add = function( key, value ) {
691                                 // If value is a function, invoke it and return its value
692                                 value = jQuery.isFunction( value ) ? value() : value;
693                                 s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
694                         };
695
696                 // Set traditional to true for jQuery <= 1.3.2 behavior.
697                 if ( traditional === undefined ) {
698                         traditional = jQuery.ajaxSettings.traditional;
699                 }
700
701                 // If an array was passed in, assume that it is an array of form elements.
702                 if ( jQuery.isArray( a ) || a.jquery ) {
703                         // Serialize the form elements
704                         jQuery.each( a, function() {
705                                 add( this.name, this.value );
706                         } );
707
708                 } else {
709                         // If traditional, encode the "old" way (the way 1.3.2 or older
710                         // did it), otherwise encode params recursively.
711                         for ( var prefix in a ) {
712                                 buildParams( prefix, a[ prefix ], traditional, add );
713                         }
714                 }
715
716                 // Return the resulting serialization
717                 return s.join( "&" ).replace( r20, "+" );
718         }
719 });
720
721 function buildParams( prefix, obj, traditional, add ) {
722         if ( jQuery.isArray( obj ) && obj.length ) {
723                 // Serialize array item.
724                 jQuery.each( obj, function( i, v ) {
725                         if ( traditional || rbracket.test( prefix ) ) {
726                                 // Treat each array item as a scalar.
727                                 add( prefix, v );
728
729                         } else {
730                                 // If array item is non-scalar (array or object), encode its
731                                 // numeric index to resolve deserialization ambiguity issues.
732                                 // Note that rack (as of 1.0.0) can't currently deserialize
733                                 // nested arrays properly, and attempting to do so may cause
734                                 // a server error. Possible fixes are to modify rack's
735                                 // deserialization algorithm or to provide an option or flag
736                                 // to force array serialization to be shallow.
737                                 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
738                         }
739                 });
740
741         } else if ( !traditional && obj != null && typeof obj === "object" ) {
742                 // If we see an array here, it is empty and should be treated as an empty
743                 // object
744                 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
745                         add( prefix, "" );
746
747                 // Serialize object item.
748                 } else {
749                         for ( var name in obj ) {
750                                 buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
751                         }
752                 }
753
754         } else {
755                 // Serialize scalar item.
756                 add( prefix, obj );
757         }
758 }
759
760 // This is still on the jQuery object... for now
761 // Want to move this to jQuery.ajax some day
762 jQuery.extend({
763
764         // Counter for holding the number of active queries
765         active: 0,
766
767         // Last-Modified header cache for next request
768         lastModified: {},
769         etag: {}
770
771 });
772
773 /* Handles responses to an ajax request:
774  * - sets all responseXXX fields accordingly
775  * - finds the right dataType (mediates between content-type and expected dataType)
776  * - returns the corresponding response
777  */
778 function ajaxHandleResponses( s, jXHR, responses ) {
779
780         var contents = s.contents,
781                 dataTypes = s.dataTypes,
782                 responseFields = s.responseFields,
783                 ct,
784                 type,
785                 finalDataType,
786                 firstDataType;
787
788         // Fill responseXXX fields
789         for( type in responseFields ) {
790                 if ( type in responses ) {
791                         jXHR[ responseFields[type] ] = responses[ type ];
792                 }
793         }
794
795         // Remove auto dataType and get content-type in the process
796         while( dataTypes[ 0 ] === "*" ) {
797                 dataTypes.shift();
798                 if ( ct === undefined ) {
799                         ct = jXHR.getResponseHeader( "content-type" );
800                 }
801         }
802
803         // Check if we're dealing with a known content-type
804         if ( ct ) {
805                 for ( type in contents ) {
806                         if ( contents[ type ] && contents[ type ].test( ct ) ) {
807                                 dataTypes.unshift( type );
808                                 break;
809                         }
810                 }
811         }
812
813         // Check to see if we have a response for the expected dataType
814         if ( dataTypes[ 0 ] in responses ) {
815                 finalDataType = dataTypes[ 0 ];
816         } else {
817                 // Try convertible dataTypes
818                 for ( type in responses ) {
819                         if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
820                                 finalDataType = type;
821                                 break;
822                         }
823                         if ( !firstDataType ) {
824                                 firstDataType = type;
825                         }
826                 }
827                 // Or just use first one
828                 finalDataType = finalDataType || firstDataType;
829         }
830
831         // If we found a dataType
832         // We add the dataType to the list if needed
833         // and return the corresponding response
834         if ( finalDataType ) {
835                 if ( finalDataType !== dataTypes[ 0 ] ) {
836                         dataTypes.unshift( finalDataType );
837                 }
838                 return responses[ finalDataType ];
839         }
840 }
841
842 // Chain conversions given the request and the original response
843 function ajaxConvert( s, response ) {
844
845         // Apply the dataFilter if provided
846         if ( s.dataFilter ) {
847                 response = s.dataFilter( response, s.dataType );
848         }
849
850         var dataTypes = s.dataTypes,
851                 converters = {},
852                 i,
853                 key,
854                 length = dataTypes.length,
855                 tmp,
856                 // Current and previous dataTypes
857                 current = dataTypes[ 0 ],
858                 prev,
859                 // Conversion expression
860                 conversion,
861                 // Conversion function
862                 conv,
863                 // Conversion functions (transitive conversion)
864                 conv1,
865                 conv2;
866
867         // For each dataType in the chain
868         for( i = 1; i < length; i++ ) {
869
870                 // Create converters map
871                 // with lowercased keys
872                 if ( i === 1 ) {
873                         for( key in s.converters ) {
874                                 if( typeof key === "string" ) {
875                                         converters[ key.toLowerCase() ] = s.converters[ key ];
876                                 }
877                         }
878                 }
879
880                 // Get the dataTypes
881                 prev = current;
882                 current = dataTypes[ i ];
883
884                 // If current is auto dataType, update it to prev
885                 if( current === "*" ) {
886                         current = prev;
887                 // If no auto and dataTypes are actually different
888                 } else if ( prev !== "*" && prev !== current ) {
889
890                         // Get the converter
891                         conversion = prev + " " + current;
892                         conv = converters[ conversion ] || converters[ "* " + current ];
893
894                         // If there is no direct converter, search transitively
895                         if ( !conv ) {
896                                 conv2 = undefined;
897                                 for( conv1 in converters ) {
898                                         tmp = conv1.split( " " );
899                                         if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
900                                                 conv2 = converters[ tmp[1] + " " + current ];
901                                                 if ( conv2 ) {
902                                                         conv1 = converters[ conv1 ];
903                                                         if ( conv1 === true ) {
904                                                                 conv = conv2;
905                                                         } else if ( conv2 === true ) {
906                                                                 conv = conv1;
907                                                         }
908                                                         break;
909                                                 }
910                                         }
911                                 }
912                         }
913                         // If we found no converter, dispatch an error
914                         if ( !( conv || conv2 ) ) {
915                                 jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
916                         }
917                         // If found converter is not an equivalence
918                         if ( conv !== true ) {
919                                 // Convert with 1 or 2 converters accordingly
920                                 response = conv ? conv( response ) : conv2( conv1(response) );
921                         }
922                 }
923         }
924         return response;
925 }
926
927 })( jQuery );