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