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