Fixes #2994. Not finding a transport now fires the error callbacks and doesn't make...
[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                 return this;
165         },
166
167         ajaxSettings: {
168                 url: location.href,
169                 global: true,
170                 type: "GET",
171                 contentType: "application/x-www-form-urlencoded",
172                 processData: true,
173                 async: true,
174                 /*
175                 timeout: 0,
176                 data: null,
177                 dataType: null,
178                 dataTypes: null,
179                 username: null,
180                 password: null,
181                 cache: null,
182                 traditional: false,
183                 */
184                 xhr: function() {
185                         return new window.XMLHttpRequest();
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                 // Prefilters
203                 // 1) They are useful to introduce custom dataTypes (see transport/jsonp for an example)
204                 // 2) These are called:
205                 //    * BEFORE asking for a transport
206                 //    * AFTER param serialization (s.data is a string if s.processData is true)
207                 // 3) key is the dataType
208                 // 4) the catchall symbol "*" can be used
209                 // 5) execution will start with transport dataType and THEN continue down to "*" if needed
210                 prefilters: {},
211
212                 // Transports bindings
213                 // 1) key is the dataType
214                 // 2) the catchall symbol "*" can be used
215                 // 3) selection will start with transport dataType and THEN go to "*" if needed
216                 transports: {},
217
218                 // List of data converters
219                 // 1) key format is "source_type destination_type" (a single space in-between)
220                 // 2) the catchall symbol "*" can be used for source_type
221                 converters: {
222
223                         // Convert anything to text
224                         "* text": window.String,
225
226                         // Text to html (true = no transformation)
227                         "text html": true,
228
229                         // Evaluate text as a json expression
230                         "text json": jQuery.parseJSON,
231
232                         // Parse text as xml
233                         "text xml": jQuery.parseXML
234                 }
235         },
236
237         // Main method
238         // (s is used internally)
239         ajax: function( url , options , s ) {
240
241                 // Handle varargs
242                 if ( arguments.length === 1 ) {
243                         options = url;
244                         url = options ? options.url : undefined;
245                 }
246
247                 // Force options to be an object
248                 options = options || {};
249
250                 // Get the url if provided separately
251                 options.url = url || options.url;
252
253                 // Create the final options object
254                 s = jQuery.extend( true , {} , jQuery.ajaxSettings , options );
255
256                 // We force the original context
257                 // (plain objects used as context get extended)
258                 s.context = options.context;
259
260                 var // jQuery lists
261                         jQuery_lastModified = jQuery.lastModified,
262                         jQuery_etag = jQuery.etag,
263                         // Callbacks contexts
264                         callbackContext = s.context || s,
265                         globalEventContext = s.context ? jQuery( s.context ) : jQuery.event,
266                         // Deferreds
267                         deferred = jQuery.Deferred(),
268                         completeDeferred = jQuery._Deferred(),
269                         // Status-dependent callbacks
270                         statusCode = s.statusCode || {},
271                         // Headers (they are sent all at once)
272                         requestHeaders = {},
273                         // Response headers
274                         responseHeadersString,
275                         responseHeaders,
276                         // transport
277                         transport,
278                         // timeout handle
279                         timeoutTimer,
280                         // Cross-domain detection vars
281                         loc = document.location,
282                         parts,
283                         // The jXHR state
284                         state = 0,
285                         // Loop variable
286                         i,
287                         // Fake xhr
288                         jXHR = {
289
290                                 readyState: 0,
291
292                                 // Caches the header
293                                 setRequestHeader: function(name,value) {
294                                         if ( state === 0 ) {
295                                                 requestHeaders[ name.toLowerCase() ] = value;
296                                         }
297                                         return this;
298                                 },
299
300                                 // Raw string
301                                 getAllResponseHeaders: function() {
302                                         return state === 2 ? responseHeadersString : null;
303                                 },
304
305                                 // Builds headers hashtable if needed
306                                 // (match is used internally)
307                                 getResponseHeader: function( key , match ) {
308
309                                         if ( state === 2 ) {
310
311                                                 if ( responseHeaders === undefined ) {
312
313                                                         responseHeaders = {};
314
315                                                         if ( typeof responseHeadersString === "string" ) {
316
317                                                                 while( ( match = rheaders.exec( responseHeadersString ) ) ) {
318                                                                         responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
319                                                                 }
320                                                         }
321                                                 }
322                                                 match = responseHeaders[ key.toLowerCase() ];
323
324                                         } else {
325
326                                                 match = null;
327                                         }
328
329                                         return match;
330                                 },
331
332                                 // Cancel the request
333                                 abort: function( statusText ) {
334                                         if ( transport ) {
335                                                 transport.abort( statusText || "abort" );
336                                         }
337                                         done( 0 , statusText );
338                                         return this;
339                                 }
340                         };
341
342                 // Callback for when everything is done
343                 // It is defined here because jslint complains if it is declared
344                 // at the end of the function (which would be more logical and readable)
345                 function done( status , statusText , response , headers) {
346
347                         // Called once
348                         if ( state === 2 ) {
349                                 return;
350                         }
351
352                         // State is "done" now
353                         state = 2;
354
355                         // Dereference transport for early garbage collection
356                         // (no matter how long the jXHR transport will be used
357                         transport = 0;
358
359                         // Set readyState
360                         jXHR.readyState = status ? 4 : 0;
361
362                         // Cache response headers
363                         responseHeadersString = headers || "";
364
365                         // Clear timeout if it exists
366                         if ( timeoutTimer ) {
367                                 clearTimeout(timeoutTimer);
368                         }
369
370                         var // Reference url
371                                 url = s.url,
372                                 // and ifModified status
373                                 ifModified = s.ifModified,
374
375                                 // Is it a success?
376                                 isSuccess = 0,
377                                 // Stored success
378                                 success,
379                                 // Stored error
380                                 error;
381
382                         // If successful, handle type chaining
383                         if ( status >= 200 && status < 300 || status === 304 ) {
384
385                                 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
386                                 if ( s.ifModified ) {
387
388                                         var lastModified = jXHR.getResponseHeader("Last-Modified"),
389                                                 etag = jXHR.getResponseHeader("Etag");
390
391                                         if (lastModified) {
392                                                 jQuery_lastModified[ s.url ] = lastModified;
393                                         }
394                                         if (etag) {
395                                                 jQuery_etag[ s.url ] = etag;
396                                         }
397                                 }
398
399                                 // If not modified
400                                 if ( status === 304 ) {
401
402                                         // Set the statusText accordingly
403                                         statusText = "notmodified";
404                                         // Mark as a success
405                                         isSuccess = 1;
406
407                                 // If we have data
408                                 } else {
409
410                                         // Set the statusText accordingly
411                                         statusText = "success";
412
413                                         // Chain data conversions and determine the final value
414                                         // (if an exception is thrown in the process, it'll be notified as an error)
415                                         try {
416
417                                                 var i,
418                                                         // Current dataType
419                                                         current,
420                                                         // Previous dataType
421                                                         prev,
422                                                         // Conversion function
423                                                         conv,
424                                                         // Conversion functions (when text is used in-between)
425                                                         conv1,
426                                                         conv2,
427                                                         // Local references to dataTypes & converters
428                                                         dataTypes = s.dataTypes,
429                                                         converters = s.converters,
430                                                         // DataType to responseXXX field mapping
431                                                         responses = {
432                                                                 "xml": "XML",
433                                                                 "text": "Text"
434                                                         };
435
436                                                 // For each dataType in the chain
437                                                 for( i = 0 ; i < dataTypes.length ; i++ ) {
438
439                                                         current = dataTypes[ i ];
440
441                                                         // If a responseXXX field for this dataType exists
442                                                         // and if it hasn't been set yet
443                                                         if ( responses[ current ] ) {
444                                                                 // Set it
445                                                                 jXHR[ "response" + responses[ current ] ] = response;
446                                                                 // Mark it as set
447                                                                 responses[ current ] = 0;
448                                                         }
449
450                                                         // If this is not the first element
451                                                         if ( i ) {
452
453                                                                 // Get the dataType to convert from
454                                                                 prev = dataTypes[ i - 1 ];
455
456                                                                 // If no catch-all and dataTypes are actually different
457                                                                 if ( prev !== "*" && current !== "*" && prev !== current ) {
458
459                                                                         // Get the converter
460                                                                         conv = converters[ prev + " " + current ] ||
461                                                                                 converters[ "* " + current ];
462
463                                                                         conv1 = conv2 = 0;
464
465                                                                         // If there is no direct converter and none of the dataTypes is text
466                                                                         if ( ! conv && prev !== "text" && current !== "text" ) {
467                                                                                 // Try with text in-between
468                                                                                 conv1 = converters[ prev + " text" ] || converters[ "* text" ];
469                                                                                 conv2 = converters[ "text " + current ];
470                                                                                 // Revert back to a single converter
471                                                                                 // if one of the converter is an equivalence
472                                                                                 if ( conv1 === true ) {
473                                                                                         conv = conv2;
474                                                                                 } else if ( conv2 === true ) {
475                                                                                         conv = conv1;
476                                                                                 }
477                                                                         }
478                                                                         // If we found no converter, dispatch an error
479                                                                         if ( ! ( conv || conv1 && conv2 ) ) {
480                                                                                 throw conversion;
481                                                                         }
482                                                                         // If found converter is not an equivalence
483                                                                         if ( conv !== true ) {
484                                                                                 // Convert with 1 or 2 converters accordingly
485                                                                                 response = conv ? conv( response ) : conv2( conv1( response ) );
486                                                                         }
487                                                                 }
488                                                         // If it is the first element of the chain
489                                                         // and we have a dataFilter
490                                                         } else if ( s.dataFilter ) {
491                                                                 // Apply the dataFilter
492                                                                 response = s.dataFilter( response , current );
493                                                                 // Get dataTypes again in case the filter changed them
494                                                                 dataTypes = s.dataTypes;
495                                                         }
496                                                 }
497                                                 // End of loop
498
499                                                 // We have a real success
500                                                 success = response;
501                                                 isSuccess = 1;
502
503                                         // If an exception was thrown
504                                         } catch(e) {
505
506                                                 // We have a parsererror
507                                                 statusText = "parsererror";
508                                                 error = "" + e;
509
510                                         }
511                                 }
512
513                         // if not success, mark it as an error
514                         } else {
515
516                                         error = statusText = statusText || "error";
517
518                                         // Set responseText if needed
519                                         if ( response ) {
520                                                 jXHR.responseText = response;
521                                         }
522                         }
523
524                         // Set data for the fake xhr object
525                         jXHR.status = status;
526                         jXHR.statusText = statusText;
527
528                         // Success/Error
529                         if ( isSuccess ) {
530                                 deferred.fire( callbackContext , [ success , statusText , jXHR ] );
531                         } else {
532                                 deferred.fireReject( callbackContext , [ jXHR , statusText , error ] );
533                         }
534
535                         // Status-dependent callbacks
536                         jXHR.statusCode( statusCode );
537
538                         if ( s.global ) {
539                                 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ) ,
540                                                 [ jXHR , s , isSuccess ? success : error ] );
541                         }
542
543                         // Complete
544                         completeDeferred.fire( callbackContext, [ jXHR , statusText ] );
545
546                         if ( s.global ) {
547                                 globalEventContext.trigger( "ajaxComplete" , [ jXHR , s] );
548                                 // Handle the global AJAX counter
549                                 if ( ! --jQuery.active ) {
550                                         jQuery.event.trigger( "ajaxStop" );
551                                 }
552                         }
553                 }
554
555                 // Attach deferreds
556                 deferred.promise( jXHR );
557                 jXHR.success = jXHR.done;
558                 jXHR.error = jXHR.fail;
559                 jXHR.complete = completeDeferred.done;
560
561                 // Status-dependent callbacks
562                 jXHR.statusCode = function( map ) {
563                         if ( map ) {
564                                 var resolved = jXHR.isResolved(),
565                                         tmp;
566                                 if ( resolved || jXHR.isRejected() ) {
567                                         tmp = map[ jXHR.status ];
568                                         if ( tmp ) {
569                                                 if ( map === statusCode ) {
570                                                         delete statusCode[ jXHR.status ];
571                                                 }
572                                                 jXHR[ resolved ? "done" : "fail" ]( tmp );
573                                         }
574                                 } else {
575                                         for( tmp in map ) {
576                                                 statusCode[ tmp ] = [ statusCode[ tmp ] , map[ tmp ] ];
577                                         }
578                                 }
579                         }
580                         return this;
581                 };
582
583                 // Remove hash character (#7531: and string promotion)
584                 s.url = ( "" + s.url ).replace( rhash , "" );
585
586                 // Uppercase the type
587                 s.type = s.type.toUpperCase();
588
589                 // Determine if request has content
590                 s.hasContent = ! rnoContent.test( s.type );
591
592                 // Extract dataTypes list
593                 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( /\s+/ );
594
595                 // Determine if a cross-domain request is in order
596                 if ( ! s.crossDomain ) {
597                         parts = rurl.exec( s.url.toLowerCase() );
598                         s.crossDomain = !!(
599                                         parts &&
600                                         ( parts[ 1 ] && parts[ 1 ] != loc.protocol ||
601                                                 parts[ 2 ] != loc.hostname ||
602                                                 ( parts[ 3 ] || 80 ) != ( loc.port || 80 ) )
603                         );
604                 }
605
606                 // Convert data if not already a string
607                 if ( s.data && s.processData && typeof s.data != "string" ) {
608                         s.data = jQuery.param( s.data , s.traditional );
609                 }
610
611                 // Apply prefilters
612                 jQuery.ajaxPrefilter( s , options );
613
614                 // Watch for a new set of requests
615                 if ( s.global && jQuery.active++ === 0 ) {
616                         jQuery.event.trigger( "ajaxStart" );
617                 }
618
619                 // More options handling for requests with no content
620                 if ( ! s.hasContent ) {
621
622                         // If data is available, append data to url
623                         if ( s.data ) {
624                                 s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
625                         }
626
627                         // Add anti-cache in url if needed
628                         if ( s.cache === false ) {
629
630                                 var ts = jQuery.now(),
631                                         // try replacing _= if it is there
632                                         ret = s.url.replace( rts , "$1_=" + ts );
633
634                                 // if nothing was replaced, add timestamp to the end
635                                 s.url = ret + ( (ret == s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "");
636                         }
637                 }
638
639                 // Set the correct header, if data is being sent
640                 if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
641                         requestHeaders[ "content-type" ] = s.contentType;
642                 }
643
644                 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
645                 if ( s.ifModified ) {
646                         if ( jQuery_lastModified[ s.url ] ) {
647                                 requestHeaders[ "if-modified-since" ] = jQuery_lastModified[ s.url ];
648                         }
649                         if ( jQuery_etag[ s.url ] ) {
650                                 requestHeaders[ "if-none-match" ] = jQuery_etag[ s.url ];
651                         }
652                 }
653
654                 // Set the Accepts header for the server, depending on the dataType
655                 requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
656                         s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
657                         s.accepts[ "*" ];
658
659                 // Check for headers option
660                 for ( i in s.headers ) {
661                         requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
662                 }
663
664                 // Allow custom headers/mimetypes and early abort
665                 if ( s.beforeSend && ( s.beforeSend.call( callbackContext , jXHR , s ) === false || state === 2 ) ) {
666
667                                 // Abort if not done already
668                                 done( 0 , "abort" );
669
670                                 // Return false
671                                 jXHR = false;
672
673                 } else {
674
675                         // Install callbacks on deferreds
676                         for ( i in { success:1, error:1, complete:1 } ) {
677                                 jXHR[ i ]( s[ i ] );
678                         }
679
680                         // Get transport
681                         transport = jQuery.ajaxTransport( s );
682
683                         // If no transport, we auto-abort
684                         if ( ! transport ) {
685
686                                 done( 0 , "notransport" );
687
688                         } else {
689
690                                 // Set state as sending
691                                 state = jXHR.readyState = 1;
692
693                                 // Send global event
694                                 if ( s.global ) {
695                                         globalEventContext.trigger( "ajaxSend" , [ jXHR , s ] );
696                                 }
697
698                                 // Timeout
699                                 if ( s.async && s.timeout > 0 ) {
700                                         timeoutTimer = setTimeout(function(){
701                                                 jXHR.abort( "timeout" );
702                                         }, s.timeout);
703                                 }
704
705                                 // Try to send
706                                 try {
707                                         transport.send(requestHeaders, done);
708                                 } catch (e) {
709                                         // Propagate exception as error if not done
710                                         if ( status === 1 ) {
711
712                                                 done(0, "error", "" + e);
713                                                 jXHR = false;
714
715                                         // Simply rethrow otherwise
716                                         } else {
717                                                 jQuery.error(e);
718                                         }
719                                 }
720                         }
721                 }
722
723                 return jXHR;
724         },
725
726         // Serialize an array of form elements or a set of
727         // key/values into a query string
728         param: function( a, traditional ) {
729                 var s = [],
730                         add = function( key, value ) {
731                                 // If value is a function, invoke it and return its value
732                                 value = jQuery.isFunction(value) ? value() : value;
733                                 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
734                         };
735
736                 // Set traditional to true for jQuery <= 1.3.2 behavior.
737                 if ( traditional === undefined ) {
738                         traditional = jQuery.ajaxSettings.traditional;
739                 }
740
741                 // If an array was passed in, assume that it is an array of form elements.
742                 if ( jQuery.isArray(a) || a.jquery ) {
743                         // Serialize the form elements
744                         jQuery.each( a, function() {
745                                 add( this.name, this.value );
746                         });
747
748                 } else {
749                         // If traditional, encode the "old" way (the way 1.3.2 or older
750                         // did it), otherwise encode params recursively.
751                         for ( var prefix in a ) {
752                                 buildParams( prefix, a[prefix], traditional, add );
753                         }
754                 }
755
756                 // Return the resulting serialization
757                 return s.join("&").replace(r20, "+");
758         }
759 });
760
761 function buildParams( prefix, obj, traditional, add ) {
762         if ( jQuery.isArray(obj) && obj.length ) {
763                 // Serialize array item.
764                 jQuery.each( obj, function( i, v ) {
765                         if ( traditional || rbracket.test( prefix ) ) {
766                                 // Treat each array item as a scalar.
767                                 add( prefix, v );
768
769                         } else {
770                                 // If array item is non-scalar (array or object), encode its
771                                 // numeric index to resolve deserialization ambiguity issues.
772                                 // Note that rack (as of 1.0.0) can't currently deserialize
773                                 // nested arrays properly, and attempting to do so may cause
774                                 // a server error. Possible fixes are to modify rack's
775                                 // deserialization algorithm or to provide an option or flag
776                                 // to force array serialization to be shallow.
777                                 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
778                         }
779                 });
780
781         } else if ( !traditional && obj != null && typeof obj === "object" ) {
782                 // If we see an array here, it is empty and should be treated as an empty
783                 // object
784                 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
785                         add( prefix, "" );
786
787                 // Serialize object item.
788                 } else {
789                         jQuery.each( obj, function( k, v ) {
790                                 buildParams( prefix + "[" + k + "]", v, traditional, add );
791                         });
792                 }
793
794         } else {
795                 // Serialize scalar item.
796                 add( prefix, obj );
797         }
798 }
799
800 // This is still on the jQuery object... for now
801 // Want to move this to jQuery.ajax some day
802 jQuery.extend({
803
804         // Counter for holding the number of active queries
805         active: 0,
806
807         // Last-Modified header cache for next request
808         lastModified: {},
809         etag: {}
810
811 });
812
813 //Execute or select from functions in a given structure of options
814 function ajax_selectOrExecute( structure , s ) {
815
816         var dataTypes = s.dataTypes,
817                 transportDataType,
818                 list,
819                 selected,
820                 i,
821                 length,
822                 checked = {},
823                 flag,
824                 noSelect = structure !== "transports";
825
826         function initSearch( dataType ) {
827
828                 flag = transportDataType !== dataType && ! checked[ dataType ];
829
830                 if ( flag ) {
831
832                         checked[ dataType ] = 1;
833                         transportDataType = dataType;
834                         list = s[ structure ][ dataType ];
835                         i = -1;
836                         length = list ? list.length : 0 ;
837                 }
838
839                 return flag;
840         }
841
842         initSearch( dataTypes[ 0 ] );
843
844         for ( i = 0 ; ( noSelect || ! selected ) && i <= length ; i++ ) {
845
846                 if ( i === length ) {
847
848                         initSearch( "*" );
849
850                 } else {
851
852                         selected = list[ i ]( s , determineDataType );
853
854                         // If we got redirected to another dataType
855                         // Search there (if not in progress or already tried)
856                         if ( typeof( selected ) === "string" &&
857                                 initSearch( selected ) ) {
858
859                                 dataTypes.unshift( selected );
860                                 selected = 0;
861                         }
862                 }
863         }
864
865         return noSelect ? jQuery : selected;
866 }
867
868 // Add an element to one of the structures in ajaxSettings
869 function ajax_addElement( structure , args ) {
870
871         var i,
872                 start = 0,
873                 length = args.length,
874                 dataTypes = [ "*" ],
875                 dLength = 1,
876                 dataType,
877                 functors = [],
878                 first,
879                 append,
880                 list;
881
882         if ( length ) {
883
884                 first = jQuery.type( args[ 0 ] );
885
886                 if ( first === "object" ) {
887                         return ajax_selectOrExecute( structure , args[ 0 ] );
888                 }
889
890                 structure = jQuery.ajaxSettings[ structure ];
891
892                 if ( first !== "function" ) {
893
894                         dataTypes = args[ 0 ].toLowerCase().split(/\s+/);
895                         dLength = dataTypes.length;
896                         start = 1;
897
898                 }
899
900                 if ( dLength && start < length ) {
901
902                         functors = sliceFunc.call( args , start );
903
904                         for( i = 0 ; i < dLength ; i++ ) {
905
906                                 dataType = dataTypes[ i ];
907
908                                 first = /^\+/.test( dataType );
909
910                                 if (first) {
911                                         dataType = dataType.substr(1);
912                                 }
913
914                                 if ( dataType !== "" ) {
915
916                                         append = Array.prototype[ first ? "unshift" : "push" ];
917                                         list = structure[ dataType ] = structure[ dataType ] || [];
918                                         append.apply( list , functors );
919                                 }
920                         }
921                 }
922         }
923
924         return jQuery;
925 }
926
927 // Install prefilter & transport methods
928 jQuery.each( [ "Prefilter" , "Transport" ] , function( _ , name ) {
929         _ = name.toLowerCase() + "s";
930         jQuery[ "ajax" + name ] = function() {
931                 return ajax_addElement( _ , arguments );
932         };
933 } );
934
935 // Utility function that handles dataType when response is received
936 // (for those transports that can give text or xml responses)
937 function determineDataType( s , ct , text , xml ) {
938
939         var contents = s.contents,
940                 type,
941                 regexp,
942                 dataTypes = s.dataTypes,
943                 transportDataType = dataTypes[0],
944                 response;
945
946         // Auto (xml, json, script or text determined given headers)
947         if ( transportDataType === "*" ) {
948
949                 for ( type in contents ) {
950                         if ( ( regexp = contents[ type ] ) && regexp.test( ct ) ) {
951                                 transportDataType = dataTypes[0] = type;
952                                 break;
953                         }
954                 }
955         }
956
957         // xml and parsed as such
958         if ( transportDataType === "xml" &&
959                 xml &&
960                 xml.documentElement /* #4958 */ ) {
961
962                 response = xml;
963
964         // Text response was provided
965         } else {
966
967                 response = text;
968
969                 // If it's not really text, defer to converters
970                 if ( transportDataType !== "text" ) {
971                         dataTypes.unshift( "text" );
972                 }
973
974         }
975
976         return response;
977 }
978
979 /*
980  * Create the request object; Microsoft failed to properly
981  * implement the XMLHttpRequest in IE7 (can't request local files),
982  * so we use the ActiveXObject when it is available
983  * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
984  * we need a fallback.
985  */
986 if ( window.ActiveXObject ) {
987         jQuery.ajaxSettings.xhr = function() {
988         if ( window.location.protocol !== "file:" ) {
989                 try {
990                         return new window.XMLHttpRequest();
991                 } catch( xhrError ) {}
992         }
993
994         try {
995                 return new window.ActiveXObject("Microsoft.XMLHTTP");
996         } catch( activeError ) {}
997         };
998 }
999
1000 var testXHR = jQuery.ajaxSettings.xhr();
1001
1002 // Does this browser support XHR requests?
1003 jQuery.support.ajax = !!testXHR;
1004
1005 // Does this browser support crossDomain XHR requests
1006 jQuery.support.cors = testXHR && "withCredentials" in testXHR;
1007
1008 })( jQuery );