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