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