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