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