Makes sure all converters keys are lowercased before any conversion is taking place...
[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                         // Headers (they are sent all at once)
354                         requestHeaders = {},
355                         // Response headers
356                         responseHeadersString,
357                         responseHeaders,
358                         // transport
359                         transport,
360                         // timeout handle
361                         timeoutTimer,
362                         // Cross-domain detection vars
363                         loc = document.location,
364                         protocol = loc.protocol || "http:",
365                         parts,
366                         // The jXHR state
367                         state = 0,
368                         // Loop variable
369                         i,
370                         // Fake xhr
371                         jXHR = {
372
373                                 readyState: 0,
374
375                                 // Caches the header
376                                 setRequestHeader: function( name, value ) {
377                                         if ( state === 0 ) {
378                                                 requestHeaders[ name.toLowerCase() ] = value;
379                                         }
380                                         return this;
381                                 },
382
383                                 // Raw string
384                                 getAllResponseHeaders: function() {
385                                         return state === 2 ? responseHeadersString : null;
386                                 },
387
388                                 // Builds headers hashtable if needed
389                                 getResponseHeader: function( key ) {
390                                         var match;
391                                         if ( state === 2 ) {
392                                                 if ( !responseHeaders ) {
393                                                         responseHeaders = {};
394                                                         while( ( match = rheaders.exec( responseHeadersString ) ) ) {
395                                                                 responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
396                                                         }
397                                                 }
398                                                 match = responseHeaders[ key.toLowerCase() ];
399                                         }
400                                         return match || null;
401                                 },
402
403                                 // Cancel the request
404                                 abort: function( statusText ) {
405                                         statusText = statusText || "abort";
406                                         if ( transport ) {
407                                                 transport.abort( statusText );
408                                         }
409                                         done( 0, statusText );
410                                         return this;
411                                 }
412                         };
413
414                 // Callback for when everything is done
415                 // It is defined here because jslint complains if it is declared
416                 // at the end of the function (which would be more logical and readable)
417                 function done( status, statusText, responses, headers) {
418
419                         // Called once
420                         if ( state === 2 ) {
421                                 return;
422                         }
423
424                         // State is "done" now
425                         state = 2;
426
427                         // Clear timeout if it exists
428                         if ( timeoutTimer ) {
429                                 clearTimeout( timeoutTimer );
430                         }
431
432                         // Dereference transport for early garbage collection
433                         // (no matter how long the jXHR object will be used)
434                         transport = undefined;
435
436                         // Cache response headers
437                         responseHeadersString = headers || "";
438
439                         // Set readyState
440                         jXHR.readyState = status ? 4 : 0;
441
442                         var isSuccess,
443                                 success,
444                                 error,
445                                 response = responses ? ajaxHandleResponses( s, jXHR, responses ) : undefined,
446                                 lastModified,
447                                 etag;
448
449                         // If successful, handle type chaining
450                         if ( status >= 200 && status < 300 || status === 304 ) {
451
452                                 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
453                                 if ( s.ifModified ) {
454
455                                         if ( ( lastModified = jXHR.getResponseHeader( "Last-Modified" ) ) ) {
456                                                 jQuery.lastModified[ s.url ] = lastModified;
457                                         }
458                                         if ( ( etag = jXHR.getResponseHeader( "Etag" ) ) ) {
459                                                 jQuery.etag[ s.url ] = etag;
460                                         }
461                                 }
462
463                                 // If not modified
464                                 if ( status === 304 ) {
465
466                                         statusText = "notmodified";
467                                         isSuccess = true;
468
469                                 // If we have data
470                                 } else {
471
472                                         try {
473                                                 success = ajaxConvert( s, response );
474                                                 statusText = "success";
475                                                 isSuccess = true;
476                                         } catch(e) {
477                                                 // We have a parsererror
478                                                 statusText = "parsererror";
479                                                 error = e;
480                                         }
481                                 }
482                         } else {
483                                 // We extract error from statusText
484                                 // then normalize statusText and status for non-aborts
485                                 error = statusText;
486                                 if( status ) {
487                                         statusText = "error";
488                                         if ( status < 0 ) {
489                                                 status = 0;
490                                         }
491                                 }
492                         }
493
494                         // Set data for the fake xhr object
495                         jXHR.status = status;
496                         jXHR.statusText = statusText;
497
498                         // Success/Error
499                         if ( isSuccess ) {
500                                 deferred.resolveWith( callbackContext, [ success, statusText, jXHR ] );
501                         } else {
502                                 deferred.rejectWith( callbackContext, [ jXHR, statusText, error ] );
503                         }
504
505                         // Status-dependent callbacks
506                         jXHR.statusCode( statusCode );
507                         statusCode = undefined;
508
509                         if ( s.global ) {
510                                 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
511                                                 [ jXHR, s, isSuccess ? success : error ] );
512                         }
513
514                         // Complete
515                         completeDeferred.resolveWith( callbackContext, [ jXHR, statusText ] );
516
517                         if ( s.global ) {
518                                 globalEventContext.trigger( "ajaxComplete", [ jXHR, s] );
519                                 // Handle the global AJAX counter
520                                 if ( !( --jQuery.active ) ) {
521                                         jQuery.event.trigger( "ajaxStop" );
522                                 }
523                         }
524                 }
525
526                 // Attach deferreds
527                 deferred.promise( jXHR );
528                 jXHR.success = jXHR.done;
529                 jXHR.error = jXHR.fail;
530                 jXHR.complete = completeDeferred.done;
531
532                 // Status-dependent callbacks
533                 jXHR.statusCode = function( map ) {
534                         if ( map ) {
535                                 var tmp;
536                                 if ( state < 2 ) {
537                                         for( tmp in map ) {
538                                                 statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
539                                         }
540                                 } else {
541                                         tmp = map[ jXHR.status ];
542                                         jXHR.then( tmp, tmp );
543                                 }
544                         }
545                         return this;
546                 };
547
548                 // Remove hash character (#7531: and string promotion)
549                 // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
550                 // We also use the url parameter if available
551                 s.url = ( "" + ( url || s.url ) ).replace( rhash, "" ).replace( rprotocol, protocol + "//" );
552
553                 // Extract dataTypes list
554                 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
555
556                 // Determine if a cross-domain request is in order
557                 if ( !s.crossDomain ) {
558                         parts = rurl.exec( s.url.toLowerCase() );
559                         s.crossDomain = !!( parts &&
560                                 ( parts[ 1 ] != protocol || parts[ 2 ] != loc.hostname ||
561                                         ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
562                                                 ( loc.port || ( protocol === "http:" ? 80 : 443 ) ) )
563                         );
564                 }
565
566                 // Convert data if not already a string
567                 if ( s.data && s.processData && typeof s.data !== "string" ) {
568                         s.data = jQuery.param( s.data, s.traditional );
569                 }
570
571                 // Apply prefilters
572                 inspectPrefiltersOrTransports( prefilters, s, options, jXHR );
573
574                 // Uppercase the type
575                 s.type = s.type.toUpperCase();
576
577                 // Determine if request has content
578                 s.hasContent = !rnoContent.test( s.type );
579
580                 // Watch for a new set of requests
581                 if ( s.global && jQuery.active++ === 0 ) {
582                         jQuery.event.trigger( "ajaxStart" );
583                 }
584
585                 // More options handling for requests with no content
586                 if ( !s.hasContent ) {
587
588                         // If data is available, append data to url
589                         if ( s.data ) {
590                                 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
591                         }
592
593                         // Add anti-cache in url if needed
594                         if ( s.cache === false ) {
595
596                                 var ts = jQuery.now(),
597                                         // try replacing _= if it is there
598                                         ret = s.url.replace( rts, "$1_=" + ts );
599
600                                 // if nothing was replaced, add timestamp to the end
601                                 s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
602                         }
603                 }
604
605                 // Set the correct header, if data is being sent
606                 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
607                         requestHeaders[ "content-type" ] = s.contentType;
608                 }
609
610                 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
611                 if ( s.ifModified ) {
612                         if ( jQuery.lastModified[ s.url ] ) {
613                                 requestHeaders[ "if-modified-since" ] = jQuery.lastModified[ s.url ];
614                         }
615                         if ( jQuery.etag[ s.url ] ) {
616                                 requestHeaders[ "if-none-match" ] = jQuery.etag[ s.url ];
617                         }
618                 }
619
620                 // Set the Accepts header for the server, depending on the dataType
621                 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
622                         s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
623                         s.accepts[ "*" ];
624
625                 // Check for headers option
626                 for ( i in s.headers ) {
627                         requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
628                 }
629
630                 // Allow custom headers/mimetypes and early abort
631                 if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jXHR, s ) === false || state === 2 ) ) {
632                                 // Abort if not done already
633                                 done( 0, "abort" );
634                                 // Return false
635                                 jXHR = false;
636
637                 } else {
638
639                         // Install callbacks on deferreds
640                         for ( i in { success: 1, error: 1, complete: 1 } ) {
641                                 jXHR[ i ]( s[ i ] );
642                         }
643
644                         // Get transport
645                         transport = inspectPrefiltersOrTransports( transports, s, options, jXHR );
646
647                         // If no transport, we auto-abort
648                         if ( !transport ) {
649                                 done( -1, "No Transport" );
650                         } else {
651                                 // Set state as sending
652                                 state = jXHR.readyState = 1;
653                                 // Send global event
654                                 if ( s.global ) {
655                                         globalEventContext.trigger( "ajaxSend", [ jXHR, s ] );
656                                 }
657                                 // Timeout
658                                 if ( s.async && s.timeout > 0 ) {
659                                         timeoutTimer = setTimeout( function(){
660                                                 jXHR.abort( "timeout" );
661                                         }, s.timeout );
662                                 }
663
664                                 try {
665                                         transport.send( requestHeaders, done );
666                                 } catch (e) {
667                                         // Propagate exception as error if not done
668                                         if ( status < 2 ) {
669                                                 done( -1, e );
670                                         // Simply rethrow otherwise
671                                         } else {
672                                                 jQuery.error( e );
673                                         }
674                                 }
675                         }
676                 }
677                 return jXHR;
678         },
679
680         // Serialize an array of form elements or a set of
681         // key/values into a query string
682         param: function( a, traditional ) {
683                 var s = [],
684                         add = function( key, value ) {
685                                 // If value is a function, invoke it and return its value
686                                 value = jQuery.isFunction( value ) ? value() : value;
687                                 s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
688                         };
689
690                 // Set traditional to true for jQuery <= 1.3.2 behavior.
691                 if ( traditional === undefined ) {
692                         traditional = jQuery.ajaxSettings.traditional;
693                 }
694
695                 // If an array was passed in, assume that it is an array of form elements.
696                 if ( jQuery.isArray( a ) || a.jquery ) {
697                         // Serialize the form elements
698                         jQuery.each( a, function() {
699                                 add( this.name, this.value );
700                         } );
701
702                 } else {
703                         // If traditional, encode the "old" way (the way 1.3.2 or older
704                         // did it), otherwise encode params recursively.
705                         for ( var prefix in a ) {
706                                 buildParams( prefix, a[ prefix ], traditional, add );
707                         }
708                 }
709
710                 // Return the resulting serialization
711                 return s.join( "&" ).replace( r20, "+" );
712         }
713 });
714
715 function buildParams( prefix, obj, traditional, add ) {
716         if ( jQuery.isArray( obj ) && obj.length ) {
717                 // Serialize array item.
718                 jQuery.each( obj, function( i, v ) {
719                         if ( traditional || rbracket.test( prefix ) ) {
720                                 // Treat each array item as a scalar.
721                                 add( prefix, v );
722
723                         } else {
724                                 // If array item is non-scalar (array or object), encode its
725                                 // numeric index to resolve deserialization ambiguity issues.
726                                 // Note that rack (as of 1.0.0) can't currently deserialize
727                                 // nested arrays properly, and attempting to do so may cause
728                                 // a server error. Possible fixes are to modify rack's
729                                 // deserialization algorithm or to provide an option or flag
730                                 // to force array serialization to be shallow.
731                                 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
732                         }
733                 });
734
735         } else if ( !traditional && obj != null && typeof obj === "object" ) {
736                 // If we see an array here, it is empty and should be treated as an empty
737                 // object
738                 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
739                         add( prefix, "" );
740
741                 // Serialize object item.
742                 } else {
743                         for ( var name in obj ) {
744                                 buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
745                         }
746                 }
747
748         } else {
749                 // Serialize scalar item.
750                 add( prefix, obj );
751         }
752 }
753
754 // This is still on the jQuery object... for now
755 // Want to move this to jQuery.ajax some day
756 jQuery.extend({
757
758         // Counter for holding the number of active queries
759         active: 0,
760
761         // Last-Modified header cache for next request
762         lastModified: {},
763         etag: {}
764
765 });
766
767 /* Handles responses to an ajax request:
768  * - sets all responseXXX fields accordingly
769  * - finds the right dataType (mediates between content-type and expected dataType)
770  * - returns the corresponding response
771  */
772 function ajaxHandleResponses( s, jXHR, responses ) {
773
774         var contents = s.contents,
775                 dataTypes = s.dataTypes,
776                 responseFields = s.responseFields,
777                 ct,
778                 type,
779                 finalDataType,
780                 firstDataType;
781
782         // Fill responseXXX fields
783         for( type in responseFields ) {
784                 if ( type in responses ) {
785                         jXHR[ responseFields[type] ] = responses[ type ];
786                 }
787         }
788
789         // Remove auto dataType and get content-type in the process
790         while( dataTypes[ 0 ] === "*" ) {
791                 dataTypes.shift();
792                 if ( ct === undefined ) {
793                         ct = jXHR.getResponseHeader( "content-type" );
794                 }
795         }
796
797         // Check if we're dealing with a known content-type
798         if ( ct ) {
799                 for ( type in contents ) {
800                         if ( contents[ type ] && contents[ type ].test( ct ) ) {
801                                 dataTypes.unshift( type );
802                                 break;
803                         }
804                 }
805         }
806
807         // Check to see if we have a response for the expected dataType
808         if ( dataTypes[ 0 ] in responses ) {
809                 finalDataType = dataTypes[ 0 ];
810         } else {
811                 // Try convertible dataTypes
812                 for ( type in responses ) {
813                         if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
814                                 finalDataType = type;
815                                 break;
816                         }
817                         if ( !firstDataType ) {
818                                 firstDataType = type;
819                         }
820                 }
821                 // Or just use first one
822                 finalDataType = finalDataType || firstDataType;
823         }
824
825         // If we found a dataType
826         // We add the dataType to the list if needed
827         // and return the corresponding response
828         if ( finalDataType ) {
829                 if ( finalDataType !== dataTypes[ 0 ] ) {
830                         dataTypes.unshift( finalDataType );
831                 }
832                 return responses[ finalDataType ];
833         }
834 }
835
836 // Chain conversions given the request and the original response
837 function ajaxConvert( s, response ) {
838
839         // Apply the dataFilter if provided
840         if ( s.dataFilter ) {
841                 response = s.dataFilter( response, s.dataType );
842         }
843
844         var dataTypes = s.dataTypes,
845                 converters = {},
846                 i,
847                 key,
848                 length = dataTypes.length,
849                 tmp,
850                 // Current and previous dataTypes
851                 current = dataTypes[ 0 ],
852                 prev,
853                 // Conversion expression
854                 conversion,
855                 // Conversion function
856                 conv,
857                 // Conversion functions (transitive conversion)
858                 conv1,
859                 conv2;
860
861         // For each dataType in the chain
862         for( i = 1; i < length; i++ ) {
863
864                 // Create converters map
865                 // with lowercased keys
866                 if ( i === 1 ) {
867                         for( key in s.converters ) {
868                                 if( typeof key === "string" ) {
869                                         converters[ key.toLowerCase() ] = s.converters[ key ];
870                                 }
871                         }
872                 }
873
874                 // Get the dataTypes
875                 prev = current;
876                 current = dataTypes[ i ];
877
878                 // If current is auto dataType, update it to prev
879                 if( current === "*" ) {
880                         current = prev;
881                 // If no auto and dataTypes are actually different
882                 } else if ( prev !== "*" && prev !== current ) {
883
884                         // Get the converter
885                         conversion = prev + " " + current;
886                         conv = converters[ conversion ] || converters[ "* " + current ];
887
888                         // If there is no direct converter, search transitively
889                         if ( !conv ) {
890                                 conv2 = undefined;
891                                 for( conv1 in converters ) {
892                                         tmp = conv1.split( " " );
893                                         if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
894                                                 conv2 = converters[ tmp[1] + " " + current ];
895                                                 if ( conv2 ) {
896                                                         conv1 = converters[ conv1 ];
897                                                         if ( conv1 === true ) {
898                                                                 conv = conv2;
899                                                         } else if ( conv2 === true ) {
900                                                                 conv = conv1;
901                                                         }
902                                                         break;
903                                                 }
904                                         }
905                                 }
906                         }
907                         // If we found no converter, dispatch an error
908                         if ( !( conv || conv2 ) ) {
909                                 jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
910                         }
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) );
915                         }
916                 }
917         }
918         return response;
919 }
920
921 })( jQuery );