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