Re-adds hastily removed variable and simplifies statusCode based callbacks handling.
[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
235         // Main method
236         ajax: function( url , options ) {
237
238                 // Handle varargs
239                 if ( arguments.length === 1 ) {
240                         options = url;
241                         url = options ? options.url : undefined;
242                 }
243
244                 // Force options to be an object
245                 options = options || {};
246
247                 // Get the url if provided separately
248                 options.url = url || options.url;
249
250                 var // Create the final options object
251                         s = jQuery.extend( true , {} , jQuery.ajaxSettings , options ),
252                         // jQuery lists
253                         jQuery_lastModified = jQuery.lastModified,
254                         jQuery_etag = jQuery.etag,
255                         // Callbacks contexts
256                         callbackContext = options.context || s.context || s,
257                         globalEventContext = callbackContext === s ? jQuery.event : jQuery( callbackContext ),
258                         // Deferreds
259                         deferred = jQuery.Deferred(),
260                         completeDeferred = jQuery._Deferred(),
261                         // Status-dependent callbacks
262                         statusCode = s.statusCode || {},
263                         // Headers (they are sent all at once)
264                         requestHeaders = {},
265                         // Response headers
266                         responseHeadersString,
267                         responseHeaders,
268                         // transport
269                         transport,
270                         // timeout handle
271                         timeoutTimer,
272                         // Cross-domain detection vars
273                         loc = document.location,
274                         parts,
275                         // The jXHR state
276                         state = 0,
277                         // Loop variable
278                         i,
279                         // Fake xhr
280                         jXHR = {
281
282                                 readyState: 0,
283
284                                 // Caches the header
285                                 setRequestHeader: function(name,value) {
286                                         if ( state === 0 ) {
287                                                 requestHeaders[ name.toLowerCase() ] = value;
288                                         }
289                                         return this;
290                                 },
291
292                                 // Raw string
293                                 getAllResponseHeaders: function() {
294                                         return state === 2 ? responseHeadersString : null;
295                                 },
296
297                                 // Builds headers hashtable if needed
298                                 getResponseHeader: function( key ) {
299
300                                         var match;
301
302                                         if ( state === 2 ) {
303
304                                                 if ( !responseHeaders ) {
305
306                                                         responseHeaders = {};
307
308                                                         while( ( match = rheaders.exec( responseHeadersString ) ) ) {
309                                                                 responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
310                                                         }
311                                                 }
312                                                 match = responseHeaders[ key.toLowerCase() ];
313
314                                         }
315
316                                         return match || null;
317                                 },
318
319                                 // Cancel the request
320                                 abort: function( statusText ) {
321                                         if ( transport ) {
322                                                 transport.abort( statusText || "abort" );
323                                         }
324                                         done( 0 , statusText );
325                                         return this;
326                                 }
327                         };
328
329                 // We force the original context
330                 // (plain objects used as context get extended)
331                 s.context = options.context;
332
333                 // Callback for when everything is done
334                 // It is defined here because jslint complains if it is declared
335                 // at the end of the function (which would be more logical and readable)
336                 function done( status , statusText , response , headers) {
337
338                         // Called once
339                         if ( state === 2 ) {
340                                 return;
341                         }
342
343                         // State is "done" now
344                         state = 2;
345
346                         // Dereference transport for early garbage collection
347                         // (no matter how long the jXHR transport will be used
348                         transport = undefined;
349
350                         // Set readyState
351                         jXHR.readyState = status ? 4 : 0;
352
353                         // Cache response headers
354                         responseHeadersString = headers || "";
355
356                         // Clear timeout if it exists
357                         if ( timeoutTimer ) {
358                                 clearTimeout(timeoutTimer);
359                         }
360
361                         var // Reference url
362                                 url = s.url,
363                                 // and ifModified status
364                                 ifModified = s.ifModified,
365
366                                 // Is it a success?
367                                 isSuccess = 0,
368                                 // Stored success
369                                 success,
370                                 // Stored error
371                                 error,
372
373                                 // Keep track of statusCode callbacks
374                                 oldStatusCode = statusCode;
375
376                         statusCode = undefined;
377
378                         // If successful, handle type chaining
379                         if ( status >= 200 && status < 300 || status === 304 ) {
380
381                                 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
382                                 if ( s.ifModified ) {
383
384                                         var lastModified = jXHR.getResponseHeader("Last-Modified"),
385                                                 etag = jXHR.getResponseHeader("Etag");
386
387                                         if (lastModified) {
388                                                 jQuery_lastModified[ s.url ] = lastModified;
389                                         }
390                                         if (etag) {
391                                                 jQuery_etag[ s.url ] = etag;
392                                         }
393                                 }
394
395                                 // If not modified
396                                 if ( status === 304 ) {
397
398                                         // Set the statusText accordingly
399                                         statusText = "notmodified";
400                                         // Mark as a success
401                                         isSuccess = 1;
402
403                                 // If we have data
404                                 } else {
405
406                                         // Set the statusText accordingly
407                                         statusText = "success";
408
409                                         // Chain data conversions and determine the final value
410                                         // (if an exception is thrown in the process, it'll be notified as an error)
411                                         try {
412
413                                                 var i,
414                                                         // Current dataType
415                                                         current,
416                                                         // Previous dataType
417                                                         prev,
418                                                         // Conversion expression
419                                                         conversion,
420                                                         // Conversion function
421                                                         conv,
422                                                         // Conversion functions (when text is used in-between)
423                                                         conv1,
424                                                         conv2,
425                                                         // Local references to dataTypes & converters
426                                                         dataTypes = s.dataTypes,
427                                                         converters = s.converters,
428                                                         // DataType to responseXXX field mapping
429                                                         responses = {
430                                                                 "xml": "XML",
431                                                                 "text": "Text"
432                                                         };
433
434                                                 // For each dataType in the chain
435                                                 for( i = 0 ; i < dataTypes.length ; i++ ) {
436
437                                                         current = dataTypes[ i ];
438
439                                                         // If a responseXXX field for this dataType exists
440                                                         // and if it hasn't been set yet
441                                                         if ( responses[ current ] ) {
442                                                                 // Set it
443                                                                 jXHR[ "response" + responses[ current ] ] = response;
444                                                                 // Mark it as set
445                                                                 responses[ current ] = 0;
446                                                         }
447
448                                                         // If this is not the first element
449                                                         if ( i ) {
450
451                                                                 // Get the dataType to convert from
452                                                                 prev = dataTypes[ i - 1 ];
453
454                                                                 // If no catch-all and dataTypes are actually different
455                                                                 if ( prev !== "*" && current !== "*" && prev !== current ) {
456
457                                                                         // Get the converter
458                                                                         conversion = prev + " " + current;
459                                                                         conv = converters[ conversion ] || converters[ "* " + current ];
460
461                                                                         conv1 = conv2 = 0;
462
463                                                                         // If there is no direct converter and none of the dataTypes is text
464                                                                         if ( ! conv && prev !== "text" && current !== "text" ) {
465                                                                                 // Try with text in-between
466                                                                                 conv1 = converters[ prev + " text" ] || converters[ "* text" ];
467                                                                                 conv2 = converters[ "text " + current ];
468                                                                                 // Revert back to a single converter
469                                                                                 // if one of the converter is an equivalence
470                                                                                 if ( conv1 === true ) {
471                                                                                         conv = conv2;
472                                                                                 } else if ( conv2 === true ) {
473                                                                                         conv = conv1;
474                                                                                 }
475                                                                         }
476                                                                         // If we found no converter, dispatch an error
477                                                                         if ( ! ( conv || conv1 && conv2 ) ) {
478                                                                                 throw conversion;
479                                                                         }
480                                                                         // If found converter is not an equivalence
481                                                                         if ( conv !== true ) {
482                                                                                 // Convert with 1 or 2 converters accordingly
483                                                                                 response = conv ? conv( response ) : conv2( conv1( response ) );
484                                                                         }
485                                                                 }
486                                                         // If it is the first element of the chain
487                                                         // and we have a dataFilter
488                                                         } else if ( s.dataFilter ) {
489                                                                 // Apply the dataFilter
490                                                                 response = s.dataFilter( response , current );
491                                                                 // Get dataTypes again in case the filter changed them
492                                                                 dataTypes = s.dataTypes;
493                                                         }
494                                                 }
495                                                 // End of loop
496
497                                                 // We have a real success
498                                                 success = response;
499                                                 isSuccess = 1;
500
501                                         // If an exception was thrown
502                                         } catch(e) {
503
504                                                 // We have a parsererror
505                                                 statusText = "parsererror";
506                                                 error = "" + e;
507
508                                         }
509                                 }
510
511                         // if not success, mark it as an error
512                         } else {
513
514                                         error = statusText = statusText || "error";
515
516                                         // Set responseText if needed
517                                         if ( response ) {
518                                                 jXHR.responseText = response;
519                                         }
520                         }
521
522                         // Set data for the fake xhr object
523                         jXHR.status = status;
524                         jXHR.statusText = statusText;
525
526                         // Success/Error
527                         if ( isSuccess ) {
528                                 deferred.fire( callbackContext , [ success , statusText , jXHR ] );
529                         } else {
530                                 deferred.fireReject( callbackContext , [ jXHR , statusText , error ] );
531                         }
532
533                         // Status-dependent callbacks
534                         jXHR.statusCode( oldStatusCode );
535
536                         if ( s.global ) {
537                                 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ) ,
538                                                 [ jXHR , s , isSuccess ? success : error ] );
539                         }
540
541                         // Complete
542                         completeDeferred.fire( callbackContext, [ jXHR , statusText ] );
543
544                         if ( s.global ) {
545                                 globalEventContext.trigger( "ajaxComplete" , [ jXHR , s] );
546                                 // Handle the global AJAX counter
547                                 if ( ! --jQuery.active ) {
548                                         jQuery.event.trigger( "ajaxStop" );
549                                 }
550                         }
551                 }
552
553                 // Attach deferreds
554                 deferred.promise( jXHR );
555                 jXHR.success = jXHR.done;
556                 jXHR.error = jXHR.fail;
557                 jXHR.complete = completeDeferred.done;
558
559                 // Status-dependent callbacks
560                 jXHR.statusCode = function( map ) {
561                         if ( map ) {
562                                 var tmp;
563                                 if ( statusCode ) {
564                                         for( tmp in map ) {
565                                                 statusCode[ tmp ] = [ statusCode[ tmp ] , map[ tmp ] ];
566                                         }
567                                 } else {
568                                         tmp = map[ jXHR.status ];
569                                         jXHR.done( tmp ).fail( tmp );
570                                 }
571                         }
572                         return this;
573                 };
574
575                 // Remove hash character (#7531: and string promotion)
576                 s.url = ( "" + s.url ).replace( rhash , "" );
577
578                 // Extract dataTypes list
579                 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( /\s+/ );
580
581                 // Determine if a cross-domain request is in order
582                 if ( ! s.crossDomain ) {
583                         parts = rurl.exec( s.url.toLowerCase() );
584                         s.crossDomain = !!(
585                                         parts &&
586                                         ( parts[ 1 ] && parts[ 1 ] != loc.protocol ||
587                                                 parts[ 2 ] != loc.hostname ||
588                                                 ( parts[ 3 ] || 80 ) != ( loc.port || 80 ) )
589                         );
590                 }
591
592                 // Convert data if not already a string
593                 if ( s.data && s.processData && typeof s.data !== "string" ) {
594                         s.data = jQuery.param( s.data , s.traditional );
595                 }
596
597                 // Apply prefilters
598                 jQuery.ajaxPrefilter( s , options );
599
600                 // Uppercase the type
601                 s.type = s.type.toUpperCase();
602
603                 // Determine if request has content
604                 s.hasContent = ! rnoContent.test( s.type );
605
606                 // Watch for a new set of requests
607                 if ( s.global && jQuery.active++ === 0 ) {
608                         jQuery.event.trigger( "ajaxStart" );
609                 }
610
611                 // More options handling for requests with no content
612                 if ( ! s.hasContent ) {
613
614                         // If data is available, append data to url
615                         if ( s.data ) {
616                                 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
617                         }
618
619                         // Add anti-cache in url if needed
620                         if ( s.cache === false ) {
621
622                                 var ts = jQuery.now(),
623                                         // try replacing _= if it is there
624                                         ret = s.url.replace( rts , "$1_=" + ts );
625
626                                 // if nothing was replaced, add timestamp to the end
627                                 s.url = ret + ( (ret == s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "");
628                         }
629                 }
630
631                 // Set the correct header, if data is being sent
632                 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
633                         requestHeaders[ "content-type" ] = s.contentType;
634                 }
635
636                 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
637                 if ( s.ifModified ) {
638                         if ( jQuery_lastModified[ s.url ] ) {
639                                 requestHeaders[ "if-modified-since" ] = jQuery_lastModified[ s.url ];
640                         }
641                         if ( jQuery_etag[ s.url ] ) {
642                                 requestHeaders[ "if-none-match" ] = jQuery_etag[ s.url ];
643                         }
644                 }
645
646                 // Set the Accepts header for the server, depending on the dataType
647                 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
648                         s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
649                         s.accepts[ "*" ];
650
651                 // Check for headers option
652                 for ( i in s.headers ) {
653                         requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
654                 }
655
656                 // Allow custom headers/mimetypes and early abort
657                 if ( s.beforeSend && ( s.beforeSend.call( callbackContext , jXHR , s ) === false || state === 2 ) ) {
658
659                                 // Abort if not done already
660                                 done( 0 , "abort" );
661
662                                 // Return false
663                                 jXHR = false;
664
665                 } else {
666
667                         // Install callbacks on deferreds
668                         for ( i in { success:1, error:1, complete:1 } ) {
669                                 jXHR[ i ]( s[ i ] );
670                         }
671
672                         // Get transport
673                         transport = jQuery.ajaxTransport( s );
674
675                         // If no transport, we auto-abort
676                         if ( ! transport ) {
677
678                                 done( 0 , "notransport" );
679
680                         } else {
681
682                                 // Set state as sending
683                                 state = jXHR.readyState = 1;
684
685                                 // Send global event
686                                 if ( s.global ) {
687                                         globalEventContext.trigger( "ajaxSend" , [ jXHR , s ] );
688                                 }
689
690                                 // Timeout
691                                 if ( s.async && s.timeout > 0 ) {
692                                         timeoutTimer = setTimeout(function(){
693                                                 jXHR.abort( "timeout" );
694                                         }, s.timeout);
695                                 }
696
697                                 // Try to send
698                                 try {
699                                         transport.send(requestHeaders, done);
700                                 } catch (e) {
701                                         // Propagate exception as error if not done
702                                         if ( status === 1 ) {
703
704                                                 done(0, "error", "" + e);
705                                                 jXHR = false;
706
707                                         // Simply rethrow otherwise
708                                         } else {
709                                                 jQuery.error(e);
710                                         }
711                                 }
712                         }
713                 }
714
715                 return jXHR;
716         },
717
718         // Serialize an array of form elements or a set of
719         // key/values into a query string
720         param: function( a, traditional ) {
721                 var s = [],
722                         add = function( key, value ) {
723                                 // If value is a function, invoke it and return its value
724                                 value = jQuery.isFunction(value) ? value() : value;
725                                 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
726                         };
727
728                 // Set traditional to true for jQuery <= 1.3.2 behavior.
729                 if ( traditional === undefined ) {
730                         traditional = jQuery.ajaxSettings.traditional;
731                 }
732
733                 // If an array was passed in, assume that it is an array of form elements.
734                 if ( jQuery.isArray(a) || a.jquery ) {
735                         // Serialize the form elements
736                         jQuery.each( a, function() {
737                                 add( this.name, this.value );
738                         });
739
740                 } else {
741                         // If traditional, encode the "old" way (the way 1.3.2 or older
742                         // did it), otherwise encode params recursively.
743                         for ( var prefix in a ) {
744                                 buildParams( prefix, a[prefix], traditional, add );
745                         }
746                 }
747
748                 // Return the resulting serialization
749                 return s.join("&").replace(r20, "+");
750         }
751 });
752
753 function buildParams( prefix, obj, traditional, add ) {
754         if ( jQuery.isArray(obj) && obj.length ) {
755                 // Serialize array item.
756                 jQuery.each( obj, function( i, v ) {
757                         if ( traditional || rbracket.test( prefix ) ) {
758                                 // Treat each array item as a scalar.
759                                 add( prefix, v );
760
761                         } else {
762                                 // If array item is non-scalar (array or object), encode its
763                                 // numeric index to resolve deserialization ambiguity issues.
764                                 // Note that rack (as of 1.0.0) can't currently deserialize
765                                 // nested arrays properly, and attempting to do so may cause
766                                 // a server error. Possible fixes are to modify rack's
767                                 // deserialization algorithm or to provide an option or flag
768                                 // to force array serialization to be shallow.
769                                 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
770                         }
771                 });
772
773         } else if ( !traditional && obj != null && typeof obj === "object" ) {
774                 // If we see an array here, it is empty and should be treated as an empty
775                 // object
776                 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
777                         add( prefix, "" );
778
779                 // Serialize object item.
780                 } else {
781                         jQuery.each( obj, function( k, v ) {
782                                 buildParams( prefix + "[" + k + "]", v, traditional, add );
783                         });
784                 }
785
786         } else {
787                 // Serialize scalar item.
788                 add( prefix, obj );
789         }
790 }
791
792 // This is still on the jQuery object... for now
793 // Want to move this to jQuery.ajax some day
794 jQuery.extend({
795
796         // Counter for holding the number of active queries
797         active: 0,
798
799         // Last-Modified header cache for next request
800         lastModified: {},
801         etag: {}
802
803 });
804
805 //Execute or select from functions in a given structure of options
806 function ajax_selectOrExecute( structure , s ) {
807
808         var dataTypes = s.dataTypes,
809                 transportDataType,
810                 list,
811                 selected,
812                 i,
813                 length,
814                 checked = {},
815                 flag,
816                 noSelect = structure !== "transports";
817
818         function initSearch( dataType ) {
819
820                 flag = transportDataType !== dataType && ! checked[ dataType ];
821
822                 if ( flag ) {
823
824                         checked[ dataType ] = 1;
825                         transportDataType = dataType;
826                         list = s[ structure ][ dataType ];
827                         i = -1;
828                         length = list ? list.length : 0 ;
829                 }
830
831                 return flag;
832         }
833
834         initSearch( dataTypes[ 0 ] );
835
836         for ( i = 0 ; ( noSelect || ! selected ) && i <= length ; i++ ) {
837
838                 if ( i === length ) {
839
840                         initSearch( "*" );
841
842                 } else {
843
844                         selected = list[ i ]( s , determineDataType );
845
846                         // If we got redirected to another dataType
847                         // Search there (if not in progress or already tried)
848                         if ( typeof( selected ) === "string" &&
849                                 initSearch( selected ) ) {
850
851                                 dataTypes.unshift( selected );
852                                 selected = 0;
853                         }
854                 }
855         }
856
857         return noSelect ? jQuery : selected;
858 }
859
860 // Add an element to one of the structures in ajaxSettings
861 function ajax_addElement( structure , args ) {
862
863         var i,
864                 start = 0,
865                 length = args.length,
866                 dataTypes = [ "*" ],
867                 dLength = 1,
868                 dataType,
869                 functors = [],
870                 first,
871                 append,
872                 list;
873
874         if ( length ) {
875
876                 first = jQuery.type( args[ 0 ] );
877
878                 if ( first === "object" ) {
879                         return ajax_selectOrExecute( structure , args[ 0 ] );
880                 }
881
882                 structure = jQuery.ajaxSettings[ structure ];
883
884                 if ( first !== "function" ) {
885
886                         dataTypes = args[ 0 ].toLowerCase().split(/\s+/);
887                         dLength = dataTypes.length;
888                         start = 1;
889
890                 }
891
892                 if ( dLength && start < length ) {
893
894                         functors = sliceFunc.call( args , start );
895
896                         for( i = 0 ; i < dLength ; i++ ) {
897
898                                 dataType = dataTypes[ i ];
899
900                                 first = /^\+/.test( dataType );
901
902                                 if (first) {
903                                         dataType = dataType.substr(1);
904                                 }
905
906                                 if ( dataType !== "" ) {
907
908                                         append = Array.prototype[ first ? "unshift" : "push" ];
909                                         list = structure[ dataType ] = structure[ dataType ] || [];
910                                         append.apply( list , functors );
911                                 }
912                         }
913                 }
914         }
915
916         return jQuery;
917 }
918
919 // Install prefilter & transport methods
920 jQuery.each( [ "Prefilter" , "Transport" ] , function( _ , name ) {
921         _ = name.toLowerCase() + "s";
922         jQuery[ "ajax" + name ] = function() {
923                 return ajax_addElement( _ , arguments );
924         };
925 } );
926
927 // Utility function that handles dataType when response is received
928 // (for those transports that can give text or xml responses)
929 function determineDataType( s , ct , text , xml ) {
930
931         var contents = s.contents,
932                 type,
933                 regexp,
934                 dataTypes = s.dataTypes,
935                 transportDataType = dataTypes[0],
936                 response;
937
938         // Auto (xml, json, script or text determined given headers)
939         if ( transportDataType === "*" ) {
940
941                 for ( type in contents ) {
942                         if ( ( regexp = contents[ type ] ) && regexp.test( ct ) ) {
943                                 transportDataType = dataTypes[0] = type;
944                                 break;
945                         }
946                 }
947         }
948
949         // xml and parsed as such
950         if ( transportDataType === "xml" &&
951                 xml &&
952                 xml.documentElement /* #4958 */ ) {
953
954                 response = xml;
955
956         // Text response was provided
957         } else {
958
959                 response = text;
960
961                 // If it's not really text, defer to converters
962                 if ( transportDataType !== "text" ) {
963                         dataTypes.unshift( "text" );
964                 }
965
966         }
967
968         return response;
969 }
970
971 })( jQuery );