Merge branch 'master' of git://github.com/jquery/jquery into fixedbuild
[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 = /^(.*?):[ \t]*([^\r\n]*)\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 = /^(?:about|app|app\-storage|.+\-extension|file|widget):$/,
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 = undefined;
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 = undefined;
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, undefined, callback, "script" );
276         },
277
278         getJSON: function( url, data, callback ) {
279                 return jQuery.get( url, data, callback, "json" );
280         },
281
282         // Creates a full fledged settings object into target
283         // with both ajaxSettings and settings fields.
284         // If target is omitted, writes into ajaxSettings.
285         ajaxSetup: function ( target, settings ) {
286                 if ( !settings ) {
287                         // Only one parameter, we extend ajaxSettings
288                         settings = target;
289                         target = jQuery.extend( true, jQuery.ajaxSettings, settings );
290                 } else {
291                         // target was provided, we extend into it
292                         jQuery.extend( true, target, jQuery.ajaxSettings, settings );
293                 }
294                 // Flatten fields we don't want deep extended
295                 for( var field in { context: 1, url: 1 } ) {
296                         if ( field in settings ) {
297                                 target[ field ] = settings[ field ];
298                         } else if( field in jQuery.ajaxSettings ) {
299                                 target[ field ] = jQuery.ajaxSettings[ field ];
300                         }
301                 }
302                 return target;
303         },
304
305         ajaxSettings: {
306                 url: ajaxLocation,
307                 isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
308                 global: true,
309                 type: "GET",
310                 contentType: "application/x-www-form-urlencoded",
311                 processData: true,
312                 async: true,
313                 /*
314                 timeout: 0,
315                 data: null,
316                 dataType: null,
317                 username: null,
318                 password: null,
319                 cache: null,
320                 traditional: false,
321                 headers: {},
322                 crossDomain: null,
323                 */
324
325                 accepts: {
326                         xml: "application/xml, text/xml",
327                         html: "text/html",
328                         text: "text/plain",
329                         json: "application/json, text/javascript",
330                         "*": "*/*"
331                 },
332
333                 contents: {
334                         xml: /xml/,
335                         html: /html/,
336                         json: /json/
337                 },
338
339                 responseFields: {
340                         xml: "responseXML",
341                         text: "responseText"
342                 },
343
344                 // List of data converters
345                 // 1) key format is "source_type destination_type" (a single space in-between)
346                 // 2) the catchall symbol "*" can be used for source_type
347                 converters: {
348
349                         // Convert anything to text
350                         "* text": window.String,
351
352                         // Text to html (true = no transformation)
353                         "text html": true,
354
355                         // Evaluate text as a json expression
356                         "text json": jQuery.parseJSON,
357
358                         // Parse text as xml
359                         "text xml": jQuery.parseXML
360                 }
361         },
362
363         ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
364         ajaxTransport: addToPrefiltersOrTransports( transports ),
365
366         // Main method
367         ajax: function( url, options ) {
368
369                 // If url is an object, simulate pre-1.5 signature
370                 if ( typeof url === "object" ) {
371                         options = url;
372                         url = undefined;
373                 }
374
375                 // Force options to be an object
376                 options = options || {};
377
378                 var // Create the final options object
379                         s = jQuery.ajaxSetup( {}, options ),
380                         // Callbacks context
381                         callbackContext = s.context || s,
382                         // Context for global events
383                         // It's the callbackContext if one was provided in the options
384                         // and if it's a DOM node or a jQuery collection
385                         globalEventContext = callbackContext !== s &&
386                                 ( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
387                                                 jQuery( callbackContext ) : jQuery.event,
388                         // Deferreds
389                         deferred = jQuery.Deferred(),
390                         completeDeferred = jQuery._Deferred(),
391                         // Status-dependent callbacks
392                         statusCode = s.statusCode || {},
393                         // ifModified key
394                         ifModifiedKey,
395                         // Headers (they are sent all at once)
396                         requestHeaders = {},
397                         // Response headers
398                         responseHeadersString,
399                         responseHeaders,
400                         // transport
401                         transport,
402                         // timeout handle
403                         timeoutTimer,
404                         // Cross-domain detection vars
405                         parts,
406                         // The jqXHR state
407                         state = 0,
408                         // To know if global events are to be dispatched
409                         fireGlobals,
410                         // Loop variable
411                         i,
412                         // Fake xhr
413                         jqXHR = {
414
415                                 readyState: 0,
416
417                                 // Caches the header
418                                 setRequestHeader: function( name, value ) {
419                                         if ( !state ) {
420                                                 requestHeaders[ name.toLowerCase().replace( rucHeaders, rucHeadersFunc ) ] = value;
421                                         }
422                                         return this;
423                                 },
424
425                                 // Raw string
426                                 getAllResponseHeaders: function() {
427                                         return state === 2 ? responseHeadersString : null;
428                                 },
429
430                                 // Builds headers hashtable if needed
431                                 getResponseHeader: function( key ) {
432                                         var match;
433                                         if ( state === 2 ) {
434                                                 if ( !responseHeaders ) {
435                                                         responseHeaders = {};
436                                                         while( ( match = rheaders.exec( responseHeadersString ) ) ) {
437                                                                 responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
438                                                         }
439                                                 }
440                                                 match = responseHeaders[ key.toLowerCase() ];
441                                         }
442                                         return match === undefined ? null : match;
443                                 },
444
445                                 // Overrides response content-type header
446                                 overrideMimeType: function( type ) {
447                                         if ( !state ) {
448                                                 s.mimeType = type;
449                                         }
450                                         return this;
451                                 },
452
453                                 // Cancel the request
454                                 abort: function( statusText ) {
455                                         statusText = statusText || "abort";
456                                         if ( transport ) {
457                                                 transport.abort( statusText );
458                                         }
459                                         done( 0, statusText );
460                                         return this;
461                                 }
462                         };
463
464                 // Callback for when everything is done
465                 // It is defined here because jslint complains if it is declared
466                 // at the end of the function (which would be more logical and readable)
467                 function done( status, statusText, responses, headers ) {
468
469                         // Called once
470                         if ( state === 2 ) {
471                                 return;
472                         }
473
474                         // State is "done" now
475                         state = 2;
476
477                         // Clear timeout if it exists
478                         if ( timeoutTimer ) {
479                                 clearTimeout( timeoutTimer );
480                         }
481
482                         // Dereference transport for early garbage collection
483                         // (no matter how long the jqXHR object will be used)
484                         transport = undefined;
485
486                         // Cache response headers
487                         responseHeadersString = headers || "";
488
489                         // Set readyState
490                         jqXHR.readyState = status ? 4 : 0;
491
492                         var isSuccess,
493                                 success,
494                                 error,
495                                 response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
496                                 lastModified,
497                                 etag;
498
499                         // If successful, handle type chaining
500                         if ( status >= 200 && status < 300 || status === 304 ) {
501
502                                 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
503                                 if ( s.ifModified ) {
504
505                                         if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
506                                                 jQuery.lastModified[ ifModifiedKey ] = lastModified;
507                                         }
508                                         if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
509                                                 jQuery.etag[ ifModifiedKey ] = etag;
510                                         }
511                                 }
512
513                                 // If not modified
514                                 if ( status === 304 ) {
515
516                                         statusText = "notmodified";
517                                         isSuccess = true;
518
519                                 // If we have data
520                                 } else {
521
522                                         try {
523                                                 success = ajaxConvert( s, response );
524                                                 statusText = "success";
525                                                 isSuccess = true;
526                                         } catch(e) {
527                                                 // We have a parsererror
528                                                 statusText = "parsererror";
529                                                 error = e;
530                                         }
531                                 }
532                         } else {
533                                 // We extract error from statusText
534                                 // then normalize statusText and status for non-aborts
535                                 error = statusText;
536                                 if( !statusText || status ) {
537                                         statusText = "error";
538                                         if ( status < 0 ) {
539                                                 status = 0;
540                                         }
541                                 }
542                         }
543
544                         // Set data for the fake xhr object
545                         jqXHR.status = status;
546                         jqXHR.statusText = statusText;
547
548                         // Success/Error
549                         if ( isSuccess ) {
550                                 deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
551                         } else {
552                                 deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
553                         }
554
555                         // Status-dependent callbacks
556                         jqXHR.statusCode( statusCode );
557                         statusCode = undefined;
558
559                         if ( fireGlobals ) {
560                                 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
561                                                 [ jqXHR, s, isSuccess ? success : error ] );
562                         }
563
564                         // Complete
565                         completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );
566
567                         if ( fireGlobals ) {
568                                 globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] );
569                                 // Handle the global AJAX counter
570                                 if ( !( --jQuery.active ) ) {
571                                         jQuery.event.trigger( "ajaxStop" );
572                                 }
573                         }
574                 }
575
576                 // Attach deferreds
577                 deferred.promise( jqXHR );
578                 jqXHR.success = jqXHR.done;
579                 jqXHR.error = jqXHR.fail;
580                 jqXHR.complete = completeDeferred.done;
581
582                 // Status-dependent callbacks
583                 jqXHR.statusCode = function( map ) {
584                         if ( map ) {
585                                 var tmp;
586                                 if ( state < 2 ) {
587                                         for( tmp in map ) {
588                                                 statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
589                                         }
590                                 } else {
591                                         tmp = map[ jqXHR.status ];
592                                         jqXHR.then( tmp, tmp );
593                                 }
594                         }
595                         return this;
596                 };
597
598                 // Remove hash character (#7531: and string promotion)
599                 // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
600                 // We also use the url parameter if available
601                 s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
602
603                 // Extract dataTypes list
604                 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
605
606                 // Determine if a cross-domain request is in order
607                 if ( !s.crossDomain ) {
608                         parts = rurl.exec( s.url.toLowerCase() );
609                         s.crossDomain = !!( parts &&
610                                 ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
611                                         ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
612                                                 ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
613                         );
614                 }
615
616                 // Convert data if not already a string
617                 if ( s.data && s.processData && typeof s.data !== "string" ) {
618                         s.data = jQuery.param( s.data, s.traditional );
619                 }
620
621                 // Apply prefilters
622                 inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
623
624                 // If request was aborted inside a prefiler, stop there
625                 if ( state === 2 ) {
626                         return false;
627                 }
628
629                 // We can fire global events as of now if asked to
630                 fireGlobals = s.global;
631
632                 // Uppercase the type
633                 s.type = s.type.toUpperCase();
634
635                 // Determine if request has content
636                 s.hasContent = !rnoContent.test( s.type );
637
638                 // Watch for a new set of requests
639                 if ( fireGlobals && jQuery.active++ === 0 ) {
640                         jQuery.event.trigger( "ajaxStart" );
641                 }
642
643                 // More options handling for requests with no content
644                 if ( !s.hasContent ) {
645
646                         // If data is available, append data to url
647                         if ( s.data ) {
648                                 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
649                         }
650
651                         // Get ifModifiedKey before adding the anti-cache parameter
652                         ifModifiedKey = s.url;
653
654                         // Add anti-cache in url if needed
655                         if ( s.cache === false ) {
656
657                                 var ts = jQuery.now(),
658                                         // try replacing _= if it is there
659                                         ret = s.url.replace( rts, "$1_=" + ts );
660
661                                 // if nothing was replaced, add timestamp to the end
662                                 s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
663                         }
664                 }
665
666                 // Set the correct header, if data is being sent
667                 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
668                         requestHeaders[ "Content-Type" ] = s.contentType;
669                 }
670
671                 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
672                 if ( s.ifModified ) {
673                         ifModifiedKey = ifModifiedKey || s.url;
674                         if ( jQuery.lastModified[ ifModifiedKey ] ) {
675                                 requestHeaders[ "If-Modified-Since" ] = jQuery.lastModified[ ifModifiedKey ];
676                         }
677                         if ( jQuery.etag[ ifModifiedKey ] ) {
678                                 requestHeaders[ "If-None-Match" ] = jQuery.etag[ ifModifiedKey ];
679                         }
680                 }
681
682                 // Set the Accepts header for the server, depending on the dataType
683                 requestHeaders.Accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
684                         s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
685                         s.accepts[ "*" ];
686
687                 // Check for headers option
688                 for ( i in s.headers ) {
689                         jqXHR.setRequestHeader( i, s.headers[ i ] );
690                 }
691
692                 // Allow custom headers/mimetypes and early abort
693                 if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
694                                 // Abort if not done already
695                                 jqXHR.abort();
696                                 return false;
697
698                 }
699
700                 // Install callbacks on deferreds
701                 for ( i in { success: 1, error: 1, complete: 1 } ) {
702                         jqXHR[ i ]( s[ i ] );
703                 }
704
705                 // Get transport
706                 transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
707
708                 // If no transport, we auto-abort
709                 if ( !transport ) {
710                         done( -1, "No Transport" );
711                 } else {
712                         jqXHR.readyState = 1;
713                         // Send global event
714                         if ( fireGlobals ) {
715                                 globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
716                         }
717                         // Timeout
718                         if ( s.async && s.timeout > 0 ) {
719                                 timeoutTimer = setTimeout( function(){
720                                         jqXHR.abort( "timeout" );
721                                 }, s.timeout );
722                         }
723
724                         try {
725                                 state = 1;
726                                 transport.send( requestHeaders, done );
727                         } catch (e) {
728                                 // Propagate exception as error if not done
729                                 if ( status < 2 ) {
730                                         done( -1, e );
731                                 // Simply rethrow otherwise
732                                 } else {
733                                         jQuery.error( e );
734                                 }
735                         }
736                 }
737
738                 return jqXHR;
739         },
740
741         // Serialize an array of form elements or a set of
742         // key/values into a query string
743         param: function( a, traditional ) {
744                 var s = [],
745                         add = function( key, value ) {
746                                 // If value is a function, invoke it and return its value
747                                 value = jQuery.isFunction( value ) ? value() : value;
748                                 s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
749                         };
750
751                 // Set traditional to true for jQuery <= 1.3.2 behavior.
752                 if ( traditional === undefined ) {
753                         traditional = jQuery.ajaxSettings.traditional;
754                 }
755
756                 // If an array was passed in, assume that it is an array of form elements.
757                 if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
758                         // Serialize the form elements
759                         jQuery.each( a, function() {
760                                 add( this.name, this.value );
761                         } );
762
763                 } else {
764                         // If traditional, encode the "old" way (the way 1.3.2 or older
765                         // did it), otherwise encode params recursively.
766                         for ( var prefix in a ) {
767                                 buildParams( prefix, a[ prefix ], traditional, add );
768                         }
769                 }
770
771                 // Return the resulting serialization
772                 return s.join( "&" ).replace( r20, "+" );
773         }
774 });
775
776 function buildParams( prefix, obj, traditional, add ) {
777         if ( jQuery.isArray( obj ) && obj.length ) {
778                 // Serialize array item.
779                 jQuery.each( obj, function( i, v ) {
780                         if ( traditional || rbracket.test( prefix ) ) {
781                                 // Treat each array item as a scalar.
782                                 add( prefix, v );
783
784                         } else {
785                                 // If array item is non-scalar (array or object), encode its
786                                 // numeric index to resolve deserialization ambiguity issues.
787                                 // Note that rack (as of 1.0.0) can't currently deserialize
788                                 // nested arrays properly, and attempting to do so may cause
789                                 // a server error. Possible fixes are to modify rack's
790                                 // deserialization algorithm or to provide an option or flag
791                                 // to force array serialization to be shallow.
792                                 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
793                         }
794                 });
795
796         } else if ( !traditional && obj != null && typeof obj === "object" ) {
797                 // If we see an array here, it is empty and should be treated as an empty
798                 // object
799                 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
800                         add( prefix, "" );
801
802                 // Serialize object item.
803                 } else {
804                         for ( var name in obj ) {
805                                 buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
806                         }
807                 }
808
809         } else {
810                 // Serialize scalar item.
811                 add( prefix, obj );
812         }
813 }
814
815 // This is still on the jQuery object... for now
816 // Want to move this to jQuery.ajax some day
817 jQuery.extend({
818
819         // Counter for holding the number of active queries
820         active: 0,
821
822         // Last-Modified header cache for next request
823         lastModified: {},
824         etag: {}
825
826 });
827
828 /* Handles responses to an ajax request:
829  * - sets all responseXXX fields accordingly
830  * - finds the right dataType (mediates between content-type and expected dataType)
831  * - returns the corresponding response
832  */
833 function ajaxHandleResponses( s, jqXHR, responses ) {
834
835         var contents = s.contents,
836                 dataTypes = s.dataTypes,
837                 responseFields = s.responseFields,
838                 ct,
839                 type,
840                 finalDataType,
841                 firstDataType;
842
843         // Fill responseXXX fields
844         for( type in responseFields ) {
845                 if ( type in responses ) {
846                         jqXHR[ responseFields[type] ] = responses[ type ];
847                 }
848         }
849
850         // Remove auto dataType and get content-type in the process
851         while( dataTypes[ 0 ] === "*" ) {
852                 dataTypes.shift();
853                 if ( ct === undefined ) {
854                         ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
855                 }
856         }
857
858         // Check if we're dealing with a known content-type
859         if ( ct ) {
860                 for ( type in contents ) {
861                         if ( contents[ type ] && contents[ type ].test( ct ) ) {
862                                 dataTypes.unshift( type );
863                                 break;
864                         }
865                 }
866         }
867
868         // Check to see if we have a response for the expected dataType
869         if ( dataTypes[ 0 ] in responses ) {
870                 finalDataType = dataTypes[ 0 ];
871         } else {
872                 // Try convertible dataTypes
873                 for ( type in responses ) {
874                         if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
875                                 finalDataType = type;
876                                 break;
877                         }
878                         if ( !firstDataType ) {
879                                 firstDataType = type;
880                         }
881                 }
882                 // Or just use first one
883                 finalDataType = finalDataType || firstDataType;
884         }
885
886         // If we found a dataType
887         // We add the dataType to the list if needed
888         // and return the corresponding response
889         if ( finalDataType ) {
890                 if ( finalDataType !== dataTypes[ 0 ] ) {
891                         dataTypes.unshift( finalDataType );
892                 }
893                 return responses[ finalDataType ];
894         }
895 }
896
897 // Chain conversions given the request and the original response
898 function ajaxConvert( s, response ) {
899
900         // Apply the dataFilter if provided
901         if ( s.dataFilter ) {
902                 response = s.dataFilter( response, s.dataType );
903         }
904
905         var dataTypes = s.dataTypes,
906                 converters = {},
907                 i,
908                 key,
909                 length = dataTypes.length,
910                 tmp,
911                 // Current and previous dataTypes
912                 current = dataTypes[ 0 ],
913                 prev,
914                 // Conversion expression
915                 conversion,
916                 // Conversion function
917                 conv,
918                 // Conversion functions (transitive conversion)
919                 conv1,
920                 conv2;
921
922         // For each dataType in the chain
923         for( i = 1; i < length; i++ ) {
924
925                 // Create converters map
926                 // with lowercased keys
927                 if ( i === 1 ) {
928                         for( key in s.converters ) {
929                                 if( typeof key === "string" ) {
930                                         converters[ key.toLowerCase() ] = s.converters[ key ];
931                                 }
932                         }
933                 }
934
935                 // Get the dataTypes
936                 prev = current;
937                 current = dataTypes[ i ];
938
939                 // If current is auto dataType, update it to prev
940                 if( current === "*" ) {
941                         current = prev;
942                 // If no auto and dataTypes are actually different
943                 } else if ( prev !== "*" && prev !== current ) {
944
945                         // Get the converter
946                         conversion = prev + " " + current;
947                         conv = converters[ conversion ] || converters[ "* " + current ];
948
949                         // If there is no direct converter, search transitively
950                         if ( !conv ) {
951                                 conv2 = undefined;
952                                 for( conv1 in converters ) {
953                                         tmp = conv1.split( " " );
954                                         if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
955                                                 conv2 = converters[ tmp[1] + " " + current ];
956                                                 if ( conv2 ) {
957                                                         conv1 = converters[ conv1 ];
958                                                         if ( conv1 === true ) {
959                                                                 conv = conv2;
960                                                         } else if ( conv2 === true ) {
961                                                                 conv = conv1;
962                                                         }
963                                                         break;
964                                                 }
965                                         }
966                                 }
967                         }
968                         // If we found no converter, dispatch an error
969                         if ( !( conv || conv2 ) ) {
970                                 jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
971                         }
972                         // If found converter is not an equivalence
973                         if ( conv !== true ) {
974                                 // Convert with 1 or 2 converters accordingly
975                                 response = conv ? conv( response ) : conv2( conv1(response) );
976                         }
977                 }
978         }
979         return response;
980 }
981
982 })( jQuery );