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