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