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