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