Replaces "text in-between" technique with a full-fledged one-level transitive search...
[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, converters and responseFields
376                                 dataTypes = s.dataTypes,
377                                 converters = s.converters,
378                                 responseFields = s.responseFields,
379                                 responseField,
380
381                                 // Flag to mark as success
382                                 isSuccess,
383                                 // Stored success
384                                 success,
385                                 // Stored error
386                                 error,
387
388                                 // To keep track of statusCode based callbacks
389                                 oldStatusCode,
390
391                                 // Actual response
392                                 response;
393
394                         // If we got responses:
395                         // - find the right one
396                         // - update dataTypes accordingly
397                         // - set responseXXX accordingly too
398                         if ( responses ) {
399
400                                 var contents = s.contents,
401                                         transportDataType = dataTypes[0],
402                                         ct,
403                                         type,
404                                         finalDataType,
405                                         firstDataType;
406
407                                 // Auto (xml, json, script or text determined given headers)
408                                 if ( transportDataType === "*" ) {
409
410                                         // Remove all auto types
411                                         while( dataTypes[0] === "*" ) {
412                                                 dataTypes.shift();
413                                         }
414                                         transportDataTypes = dataTypes[0];
415
416                                         // Get content type
417                                         ct = jXHR.getResponseHeader( "content-type" );
418
419                                         // Check if it's a known type
420                                         for ( type in contents ) {
421                                                 if ( contents[ type ] && contents[ type ].test( ct ) ) {
422                                                         dataTypes.unshift( ( transportDataType = type ) );
423                                                         break;
424                                                 }
425                                         }
426                                 }
427
428                                 // Check to see if we have a response for the expected dataType
429                                 if ( transportDataType in responses ) {
430                                         finalDataType = transportDataType;
431                                 } else {
432                                         // Try convertible dataTypes
433                                         for ( type in responses ) {
434                                                 if ( ! firstDataType ) {
435                                                         firstDataType = type;
436                                                 }
437                                                 if ( ! transportDataType || converters[ type + " " + transportDataType ] ) {
438                                                         finalDataType = type;
439                                                         break;
440                                                 }
441                                         }
442                                         // Or just use first one
443                                         finalDataType = finalDataType || firstDataType;
444                                 }
445
446                                 // If we found a dataType
447                                 // We get the corresponding response
448                                 // and add the dataType to the list if needed
449                                 if ( finalDataType ) {
450                                         response = responses[ finalDataType ];
451                                         if ( finalDataType !== transportDataType ) {
452                                                 dataTypes.unshift( finalDataType );
453                                         }
454                                 }
455
456                                 // Fill responseXXX fields
457                                 for( type in responseFields ) {
458                                         if ( type in responses ) {
459                                                 jXHR[ responseFields[ type ] ] = responses[ type ];
460                                         }
461                                 }
462                         }
463
464                         // If successful, handle type chaining
465                         if ( status >= 200 && status < 300 || status === 304 ) {
466
467                                 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
468                                 if ( s.ifModified ) {
469
470                                         var lastModified = jXHR.getResponseHeader("Last-Modified"),
471                                                 etag = jXHR.getResponseHeader("Etag");
472
473                                         if (lastModified) {
474                                                 jQuery_lastModified[ s.url ] = lastModified;
475                                         }
476                                         if (etag) {
477                                                 jQuery_etag[ s.url ] = etag;
478                                         }
479                                 }
480
481                                 // If not modified
482                                 if ( status === 304 ) {
483
484                                         statusText = "notmodified";
485                                         isSuccess = 1;
486
487                                 // If we have data
488                                 } else {
489
490                                         statusText = "success";
491
492                                         // Chain data conversions and determine the final value
493                                         // (if an exception is thrown in the process, it'll be notified as an error)
494                                         try {
495
496                                                 var i,
497                                                         tmp,
498                                                         // Current dataType
499                                                         current,
500                                                         // Previous dataType
501                                                         prev,
502                                                         // Conversion expression
503                                                         conversion,
504                                                         // Conversion function
505                                                         conv,
506                                                         // Conversion functions (when text is used in-between)
507                                                         conv1,
508                                                         conv2;
509
510                                                 // For each dataType in the chain
511                                                 for( i = 0 ; i < dataTypes.length ; i++ ) {
512
513                                                         current = dataTypes[ i ];
514
515                                                         // If a responseXXX field for this dataType exists
516                                                         // and if it hasn't been set yet
517                                                         responseField = responseFields[ current ];
518                                                         if ( responseField && ! ( responseField in jXHR ) ) {
519                                                                 jXHR[ responseField ] = response;
520                                                         }
521
522                                                         // If this is not the first element
523                                                         if ( i ) {
524
525                                                                 // Get the dataType to convert from
526                                                                 prev = dataTypes[ i - 1 ];
527
528                                                                 // If no auto and dataTypes are actually different
529                                                                 if ( prev !== "*" && current !== "*" && prev !== current ) {
530
531                                                                         // Get the converter
532                                                                         conversion = prev + " " + current;
533                                                                         conv = converters[ conversion ] || converters[ "* " + current ];
534
535                                                                         // If there is no direct converter, search transitively
536                                                                         if ( ! conv ) {
537                                                                                 conv1 = conv2 = undefined;
538
539                                                                                 for( conv1 in converters ) {
540                                                                                         tmp = conv1.split( " " );
541                                                                                         if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
542                                                                                                 conv2 = converters[ tmp[ 1 ] + " " + current ];
543                                                                                                 if ( conv2 ) {
544                                                                                                         conv1 = converters[ conv1 ];
545                                                                                                         if ( conv1 === true ) {
546                                                                                                                 conv = conv2;
547                                                                                                         } else if ( conv2 === true ) {
548                                                                                                                 conv = conv1;
549                                                                                                         }
550                                                                                                         break;
551                                                                                                 }
552                                                                                         }
553                                                                                 }
554                                                                         }
555                                                                         // If we found no converter, dispatch an error
556                                                                         if ( ! ( conv || conv1 && conv2 ) ) {
557                                                                                 throw conversion;
558                                                                         }
559                                                                         // If found converter is not an equivalence
560                                                                         if ( conv !== true ) {
561                                                                                 // Convert with 1 or 2 converters accordingly
562                                                                                 response = conv ? conv( response ) : conv2( conv1( response ) );
563                                                                         }
564                                                                 }
565                                                         // If it is the first element of the chain
566                                                         // and we have a dataFilter
567                                                         } else if ( s.dataFilter ) {
568                                                                 // Apply the dataFilter
569                                                                 response = s.dataFilter( response , current );
570                                                                 // Get dataTypes again in case the filter changed them
571                                                                 dataTypes = s.dataTypes;
572                                                         }
573                                                 }
574                                                 // End of loop
575
576                                                 // We have a real success
577                                                 success = response;
578                                                 isSuccess = 1;
579
580                                         // If an exception was thrown
581                                         } catch(e) {
582
583                                                 // We have a parsererror
584                                                 statusText = "parsererror";
585                                                 error = "" + e;
586
587                                         }
588                                 }
589
590                         // if not success, mark it as an error
591                         } else {
592                                         error = statusText = statusText || "error";
593                         }
594
595                         // Set data for the fake xhr object
596                         jXHR.status = status;
597                         jXHR.statusText = statusText;
598
599                         // Success/Error
600                         if ( isSuccess ) {
601                                 deferred.resolveWith( callbackContext , [ success , statusText , jXHR ] );
602                         } else {
603                                 deferred.rejectWith( callbackContext , [ jXHR , statusText , error ] );
604                         }
605
606                         // Status-dependent callbacks
607                         oldStatusCode = statusCode;
608                         statusCode = undefined;
609                         jXHR.statusCode( oldStatusCode );
610
611                         if ( s.global ) {
612                                 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ) ,
613                                                 [ jXHR , s , isSuccess ? success : error ] );
614                         }
615
616                         // Complete
617                         completeDeferred.resolveWith( callbackContext, [ jXHR , statusText ] );
618
619                         if ( s.global ) {
620                                 globalEventContext.trigger( "ajaxComplete" , [ jXHR , s] );
621                                 // Handle the global AJAX counter
622                                 if ( ! --jQuery.active ) {
623                                         jQuery.event.trigger( "ajaxStop" );
624                                 }
625                         }
626                 }
627
628                 // Attach deferreds
629                 deferred.promise( jXHR );
630                 jXHR.success = jXHR.done;
631                 jXHR.error = jXHR.fail;
632                 jXHR.complete = completeDeferred.done;
633
634                 // Status-dependent callbacks
635                 jXHR.statusCode = function( map ) {
636                         if ( map ) {
637                                 var tmp;
638                                 if ( statusCode ) {
639                                         for( tmp in map ) {
640                                                 statusCode[ tmp ] = [ statusCode[ tmp ] , map[ tmp ] ];
641                                         }
642                                 } else {
643                                         tmp = map[ jXHR.status ];
644                                         jXHR.done( tmp ).fail( tmp );
645                                 }
646                         }
647                         return this;
648                 };
649
650                 // Remove hash character (#7531: and string promotion)
651                 // We also use the url parameter if available
652                 s.url = ( "" + ( url || s.url ) ).replace( rhash , "" );
653
654                 // Extract dataTypes list
655                 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( /\s+/ );
656
657                 // Determine if a cross-domain request is in order
658                 if ( ! s.crossDomain ) {
659                         parts = rurl.exec( s.url.toLowerCase() );
660                         s.crossDomain = !!(
661                                         parts &&
662                                         ( parts[ 1 ] && parts[ 1 ] != protocol ||
663                                                 parts[ 2 ] != loc.hostname ||
664                                                 ( parts[ 3 ] || ( ( parts[ 1 ] || protocol ) === "http:" ? 80 : 443 ) ) !=
665                                                         ( loc.port || ( protocol === "http:" ? 80 : 443 ) ) )
666                         );
667                 }
668
669                 // Convert data if not already a string
670                 if ( s.data && s.processData && typeof s.data !== "string" ) {
671                         s.data = jQuery.param( s.data , s.traditional );
672                 }
673
674                 // Apply prefilters
675                 jQuery.ajaxPrefilter( s , options );
676
677                 // Uppercase the type
678                 s.type = s.type.toUpperCase();
679
680                 // Determine if request has content
681                 s.hasContent = ! rnoContent.test( s.type );
682
683                 // Watch for a new set of requests
684                 if ( s.global && jQuery.active++ === 0 ) {
685                         jQuery.event.trigger( "ajaxStart" );
686                 }
687
688                 // More options handling for requests with no content
689                 if ( ! s.hasContent ) {
690
691                         // If data is available, append data to url
692                         if ( s.data ) {
693                                 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
694                         }
695
696                         // Add anti-cache in url if needed
697                         if ( s.cache === false ) {
698
699                                 var ts = jQuery.now(),
700                                         // try replacing _= if it is there
701                                         ret = s.url.replace( rts , "$1_=" + ts );
702
703                                 // if nothing was replaced, add timestamp to the end
704                                 s.url = ret + ( (ret == s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "");
705                         }
706                 }
707
708                 // Set the correct header, if data is being sent
709                 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
710                         requestHeaders[ "content-type" ] = s.contentType;
711                 }
712
713                 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
714                 if ( s.ifModified ) {
715                         if ( jQuery_lastModified[ s.url ] ) {
716                                 requestHeaders[ "if-modified-since" ] = jQuery_lastModified[ s.url ];
717                         }
718                         if ( jQuery_etag[ s.url ] ) {
719                                 requestHeaders[ "if-none-match" ] = jQuery_etag[ s.url ];
720                         }
721                 }
722
723                 // Set the Accepts header for the server, depending on the dataType
724                 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
725                         s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
726                         s.accepts[ "*" ];
727
728                 // Check for headers option
729                 for ( i in s.headers ) {
730                         requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
731                 }
732
733                 // Allow custom headers/mimetypes and early abort
734                 if ( s.beforeSend && ( s.beforeSend.call( callbackContext , jXHR , s ) === false || state === 2 ) ) {
735
736                                 // Abort if not done already
737                                 done( 0 , "abort" );
738
739                                 // Return false
740                                 jXHR = false;
741
742                 } else {
743
744                         // Install callbacks on deferreds
745                         for ( i in { success:1, error:1, complete:1 } ) {
746                                 jXHR[ i ]( s[ i ] );
747                         }
748
749                         // Get transport
750                         transport = jQuery.ajaxTransport( s , options );
751
752                         // If no transport, we auto-abort
753                         if ( ! transport ) {
754
755                                 done( 0 , "notransport" );
756
757                         } else {
758
759                                 // Set state as sending
760                                 state = jXHR.readyState = 1;
761
762                                 // Send global event
763                                 if ( s.global ) {
764                                         globalEventContext.trigger( "ajaxSend" , [ jXHR , s ] );
765                                 }
766
767                                 // Timeout
768                                 if ( s.async && s.timeout > 0 ) {
769                                         timeoutTimer = setTimeout(function(){
770                                                 jXHR.abort( "timeout" );
771                                         }, s.timeout);
772                                 }
773
774                                 // Try to send
775                                 try {
776                                         transport.send(requestHeaders, done);
777                                 } catch (e) {
778                                         // Propagate exception as error if not done
779                                         if ( status === 1 ) {
780
781                                                 done(0, "error", "" + e);
782                                                 jXHR = false;
783
784                                         // Simply rethrow otherwise
785                                         } else {
786                                                 jQuery.error(e);
787                                         }
788                                 }
789                         }
790                 }
791
792                 return jXHR;
793         },
794
795         // Serialize an array of form elements or a set of
796         // key/values into a query string
797         param: function( a, traditional ) {
798                 var s = [],
799                         add = function( key, value ) {
800                                 // If value is a function, invoke it and return its value
801                                 value = jQuery.isFunction(value) ? value() : value;
802                                 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
803                         };
804
805                 // Set traditional to true for jQuery <= 1.3.2 behavior.
806                 if ( traditional === undefined ) {
807                         traditional = jQuery.ajaxSettings.traditional;
808                 }
809
810                 // If an array was passed in, assume that it is an array of form elements.
811                 if ( jQuery.isArray(a) || a.jquery ) {
812                         // Serialize the form elements
813                         jQuery.each( a, function() {
814                                 add( this.name, this.value );
815                         });
816
817                 } else {
818                         // If traditional, encode the "old" way (the way 1.3.2 or older
819                         // did it), otherwise encode params recursively.
820                         for ( var prefix in a ) {
821                                 buildParams( prefix, a[prefix], traditional, add );
822                         }
823                 }
824
825                 // Return the resulting serialization
826                 return s.join("&").replace(r20, "+");
827         }
828 });
829
830 function buildParams( prefix, obj, traditional, add ) {
831         if ( jQuery.isArray(obj) && obj.length ) {
832                 // Serialize array item.
833                 jQuery.each( obj, function( i, v ) {
834                         if ( traditional || rbracket.test( prefix ) ) {
835                                 // Treat each array item as a scalar.
836                                 add( prefix, v );
837
838                         } else {
839                                 // If array item is non-scalar (array or object), encode its
840                                 // numeric index to resolve deserialization ambiguity issues.
841                                 // Note that rack (as of 1.0.0) can't currently deserialize
842                                 // nested arrays properly, and attempting to do so may cause
843                                 // a server error. Possible fixes are to modify rack's
844                                 // deserialization algorithm or to provide an option or flag
845                                 // to force array serialization to be shallow.
846                                 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
847                         }
848                 });
849
850         } else if ( !traditional && obj != null && typeof obj === "object" ) {
851                 // If we see an array here, it is empty and should be treated as an empty
852                 // object
853                 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
854                         add( prefix, "" );
855
856                 // Serialize object item.
857                 } else {
858                         jQuery.each( obj, function( k, v ) {
859                                 buildParams( prefix + "[" + k + "]", v, traditional, add );
860                         });
861                 }
862
863         } else {
864                 // Serialize scalar item.
865                 add( prefix, obj );
866         }
867 }
868
869 // This is still on the jQuery object... for now
870 // Want to move this to jQuery.ajax some day
871 jQuery.extend({
872
873         // Counter for holding the number of active queries
874         active: 0,
875
876         // Last-Modified header cache for next request
877         lastModified: {},
878         etag: {}
879
880 });
881
882 // Base function for both ajaxPrefilter and ajaxTransport
883 function ajaxPrefilterOrTransport( arg0 , arg1 , arg2 ) {
884
885         var type = jQuery.type( arg1 ),
886                 structure = jQuery.ajaxSettings[ arg0 ],
887                 i,
888                 length;
889
890         // We have an options map so we have to inspect the structure
891         if ( type === "object" ) {
892
893                 var options = arg1,
894                         originalOptions = arg2,
895                         // When dealing with prefilters, we execute only
896                         // (no selection so we never stop when a function
897                         // returns a non-falsy, non-string value)
898                         executeOnly = ( arg0 === "prefilters" ),
899                         inspect = function( dataType, tested ) {
900
901                                 if ( ! tested[ dataType ] ) {
902
903                                         tested[ dataType ] = true;
904
905                                         var list = structure[ dataType ],
906                                                 selected;
907
908                                         for( i = 0, length = list ? list.length : 0 ; ( executeOnly || ! selected ) && i < length ; i++ ) {
909                                                 selected = list[ i ]( options , originalOptions );
910                                                 // If we got redirected to a different dataType,
911                                                 // we add it and switch to the corresponding list
912                                                 if ( typeof( selected ) === "string" && selected !== dataType ) {
913                                                         options.dataTypes.unshift( selected );
914                                                         selected = inspect( selected , tested );
915                                                         // We always break in order not to continue
916                                                         // to iterate in previous list
917                                                         break;
918                                                 }
919                                         }
920                                         // If we're only executing or nothing was selected
921                                         // we try the catchall dataType
922                                         if ( executeOnly || ! selected ) {
923                                                 selected = inspect( "*" , tested );
924                                         }
925                                         // This will be ignored by ajaxPrefilter
926                                         // so it's safe to return no matter what
927                                         return selected;
928                                 }
929
930                         };
931
932                 // Start inspection with current transport dataType
933                 return inspect( options.dataTypes[ 0 ] , {} );
934
935         } else {
936
937                 // We're requested to add to the structure
938                 // Signature is ( dataTypeExpression , function )
939                 // with dataTypeExpression being optional and
940                 // defaulting to catchAll (*)
941                 type = type === "function";
942
943                 if ( type ) {
944                         arg2 = arg1;
945                         arg1 = undefined;
946                 }
947                 arg1 = arg1 || "*";
948
949                 // We control that the second argument is really a function
950                 if ( type || jQuery.isFunction( arg2 ) ) {
951
952                         var dataTypes = arg1.split( /\s+/ ),
953                                 functor = arg2,
954                                 dataType,
955                                 list,
956                                 placeBefore;
957
958                         // For each dataType in the dataTypeExpression
959                         for( i = 0 , length = dataTypes.length ; i < length ; i++ ) {
960                                 dataType = dataTypes[ i ];
961                                 // We control if we're asked to add before
962                                 // any existing element
963                                 placeBefore = /^\+/.test( dataType );
964                                 if ( placeBefore ) {
965                                         dataType = dataType.substr( 1 );
966                                 }
967                                 list = structure[ dataType ] = structure[ dataType ] || [];
968                                 // then we add to the structure accordingly
969                                 list[ placeBefore ? "unshift" : "push" ]( functor );
970                         }
971                 }
972         }
973 }
974
975 })( jQuery );