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