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