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