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