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