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