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