Revised logic in data conversion to account for when dataFilter modifies the dataType...
[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+:)?\/\/([^\/?#]+)/,
14
15         // Slice function
16         sliceFunc = Array.prototype.slice,
17         
18         // Keep a copy of the old load method
19         _load = jQuery.fn.load;
20
21 jQuery.fn.extend({
22         load: function( url, params, callback ) {
23                 if ( typeof url !== "string" && _load ) {
24                         return _load.apply( this, arguments );
25
26                 // Don't do a request if no elements are being requested
27                 } else if ( !this.length ) {
28                         return this;
29                 }
30
31                 var off = url.indexOf(" ");
32                 if ( off >= 0 ) {
33                         var selector = url.slice(off, url.length);
34                         url = url.slice(0, off);
35                 }
36
37                 // Default to a GET request
38                 var type = "GET";
39
40                 // If the second parameter was provided
41                 if ( params ) {
42                         // If it's a function
43                         if ( jQuery.isFunction( params ) ) {
44                                 // We assume that it's the callback
45                                 callback = params;
46                                 params = null;
47
48                         // Otherwise, build a param string
49                         } else if ( typeof params === "object" ) {
50                                 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
51                                 type = "POST";
52                         }
53                 }
54                 
55                 var self = this;
56                 
57                 // Request the remote document
58                 jQuery.ajax({
59                         url: url,
60                         type: type,
61                         dataType: "html",
62                         data: params,
63                         complete: function( res, status ) {
64                                 // If successful, inject the HTML into all the matched elements
65                                 if ( status === "success" || status === "notmodified" ) {
66                                         // See if a selector was specified
67                                         self.html( selector ?
68                                                 // Create a dummy div to hold the results
69                                                 jQuery("<div>")
70                                                         // inject the contents of the document in, removing the scripts
71                                                         // to avoid any 'Permission Denied' errors in IE
72                                                         .append(res.responseText.replace(rscript, ""))
73
74                                                         // Locate the specified elements
75                                                         .find(selector) :
76
77                                                 // If not, just inject the full result
78                                                 res.responseText );
79                                 }
80
81                                 if ( callback ) {
82                                         self.each( callback, [res.responseText, status, res] );
83                                 }
84                         }
85                 });
86
87                 return this;
88         },
89
90         serialize: function() {
91                 return jQuery.param(this.serializeArray());
92         },
93
94         serializeArray: function() {
95                 return this.map(function(){
96                         return this.elements ? jQuery.makeArray(this.elements) : this;
97                 })
98                 .filter(function(){
99                         return this.name && !this.disabled &&
100                                 (this.checked || rselectTextarea.test(this.nodeName) ||
101                                         rinput.test(this.type));
102                 })
103                 .map(function(i, elem){
104                         var val = jQuery(this).val();
105
106                         return val == null ?
107                                 null :
108                                 jQuery.isArray(val) ?
109                                         jQuery.map( val, function(val, i){
110                                                 return {name: elem.name, value: val};
111                                         }) :
112                                         {name: elem.name, value: val};
113                 }).get();
114         }
115 });
116
117 // Attach a bunch of functions for handling common AJAX events
118 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function(i,o){
119         jQuery.fn[o] = function(f){
120                 return this.bind(o, f);
121         };
122 });
123
124 jQuery.extend({
125
126         get: function( url, data, callback, type ) {
127                 // shift arguments if data argument was omited
128                 if ( jQuery.isFunction( data ) ) {
129                         type = type || callback;
130                         callback = data;
131                         data = null;
132                 }
133
134                 return jQuery.ajax({
135                         type: "GET",
136                         url: url,
137                         data: data,
138                         success: callback,
139                         dataType: type
140                 });
141         },
142
143         getScript: function( url, callback ) {
144                 return jQuery.get(url, null, callback, "script");
145         },
146
147         getJSON: function( url, data, callback ) {
148                 return jQuery.get(url, data, callback, "json");
149         },
150
151         post: function( url, data, callback, type ) {
152                 // shift arguments if data argument was omited
153                 if ( jQuery.isFunction( data ) ) {
154                         type = type || callback;
155                         callback = data;
156                         data = {};
157                 }
158
159                 return jQuery.ajax({
160                         type: "POST",
161                         url: url,
162                         data: data,
163                         success: callback,
164                         dataType: type
165                 });
166         },
167
168         ajaxSetup: function( settings ) {
169                 jQuery.extend( jQuery.ajaxSettings, settings );
170         },
171
172         ajaxSettings: {
173                 url: location.href,
174                 global: true,
175                 type: "GET",
176                 contentType: "application/x-www-form-urlencoded",
177                 processData: true,
178                 async: true,
179                 /*
180                 timeout: 0,
181                 data: null,
182                 dataType: null,
183                 dataTypes: null,
184                 username: null,
185                 password: null,
186                 cache: null,
187                 traditional: false,
188                 */
189                 xhr: function() {
190                         return new window.XMLHttpRequest();
191                 },
192
193                 accepts: {
194                         xml: "application/xml, text/xml",
195                         html: "text/html",
196                         text: "text/plain",
197                         json: "application/json, text/javascript",
198                         "*": "*/*"
199                 },
200
201                 autoDataType: {
202                         xml: /xml/,
203                         html: /html/,
204                         json: /json/
205                 },
206
207                 // Prefilters
208                 // 1) They are useful to introduce custom dataTypes (see transport/jsonp for an example)
209                 // 2) These are called:
210                 //    * BEFORE asking for a transport
211                 //    * AFTER param serialization (s.data is a string if s.processData is true)
212                 // 3) key is the dataType
213                 // 4) the catchall symbol "*" can be used
214                 // 5) execution will start with transport dataType and THEN continue down to "*" if needed
215                 prefilters: {},
216
217                 // Transports bindings
218                 // 1) key is the dataType
219                 // 2) the catchall symbol "*" can be used
220                 // 3) selection will start with transport dataType and THEN go to "*" if needed
221                 transports: {},
222
223                 // List of data converters
224                 // 1) key format is "source_type destination_type" (a single space in-between)
225                 // 2) the catchall symbol "*" can be used for source_type
226                 dataConverters: {
227
228                         // Convert anything to text
229                         "* text": window.String,
230
231                         // Text to html (true = no transformation)
232                         "text html": true,
233
234                         // Evaluate text as a json expression
235                         "text json": jQuery.parseJSON,
236
237                         // Parse text as xml
238                         "text xml": jQuery.parseXML
239                 }
240         },
241
242         // Main method
243         // (s is used internally)
244         ajax: function( url , options , s ) {
245                 
246                 // Handle varargs
247                 if ( arguments.length === 1 ) {
248                         options = url;
249                         url = options ? options.url : undefined;
250                 }
251                 
252                 // Force options to be an object
253                 options = options || {};
254                 
255                 // Get the url if provided separately
256                 options.url = url || options.url;
257                 
258                 // Create the final options object
259                 s = jQuery.extend( true , {} , jQuery.ajaxSettings , options );
260                 
261                 // We force the original context
262                 // (plain objects used as context get extended)
263                 s.context = options.context;
264                 
265                 var // jQuery lists
266                         jQuery_lastModified = jQuery.lastModified,
267                         jQuery_etag = jQuery.etag,
268                         // Callbacks contexts
269                         callbackContext = s.context || s,
270                         globalEventContext = s.context ? jQuery( s.context ) : jQuery.event,
271                         // Deferreds
272                         deferred = jQuery.Deferred(),
273                         completeDeferred = jQuery._Deferred(),
274                         // Headers (they are sent all at once)
275                         requestHeaders = {},
276                         // Response headers
277                         responseHeadersString,
278                         responseHeaders,
279                         // transport
280                         transport,
281                         // timeout handle
282                         timeoutTimer,
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 = statusText;
372                         
373                         // If not timeout, force a jQuery-compliant status text
374                         if ( statusText != "timeout" ) {
375                                 statusText = ( status >= 200 && status < 300 ) ? 
376                                         "success" :
377                                         ( status === 304 ? "notmodified" : "error" );
378                         }
379                         
380                         // If successful, handle type chaining
381                         if ( statusText === "success" || statusText === "notmodified" ) {
382                                 
383                                 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
384                                 if ( s.ifModified ) {
385                                         
386                                         var lastModified = jXHR.getResponseHeader("Last-Modified"),
387                                                 etag = jXHR.getResponseHeader("Etag");
388                                                 
389                                         if (lastModified) {
390                                                 jQuery_lastModified[ s.url ] = lastModified;
391                                         }
392                                         if (etag) {
393                                                 jQuery_etag[ s.url ] = etag;
394                                         }
395                                 }
396                                 
397                                 if ( s.ifModified && statusText === "notmodified" ) {
398                                         
399                                         success = null;
400                                         isSuccess = 1;
401                                         
402                                 } else {
403                                         // Chain data conversions and determine the final value
404                                         // (if an exception is thrown in the process, it'll be notified as an error)
405                                         try {
406                                                 
407                                                 var i,
408                                                         current,
409                                                         prev,
410                                                         checker,
411                                                         conv1,
412                                                         conv2,
413                                                         oneConv,
414                                                         convertion,
415                                                         dataTypes = s.dataTypes,
416                                                         dataConverters = s.dataConverters,
417                                                         responses = {
418                                                                 "xml": "XML",
419                                                                 "text": "Text"
420                                                         };
421                                                 
422                                                 for( i = 0 ; i < dataTypes.length ; i++ ) {
423                                                         
424                                                         current = dataTypes[ i ];
425                                                         
426                                                         if ( responses[ current ] ) {
427                                                                 jXHR[ "response" + responses[ current ] ] = response;
428                                                                 responses[ current ] = 0;
429                                                         }
430                                                         
431                                                         if ( i ) {
432                                                                 
433                                                                 prev = dataTypes[ i - 1 ];
434                                                                 
435                                                                 if ( prev !== "*" && current !== "*" && prev !== current ) {
436                                                                 
437                                                                         oneConv = conv1 = 
438                                                                                 dataConverters[ ( conversion = prev + " " + current ) ] ||
439                                                                                 dataConverters[ "* " + current ];
440                                                                         
441                                                                         if ( oneConv !== true ) {
442                                                                                 
443                                                                                 if ( ! oneConv && prev !== "text" && current !== "text" ) {
444                                                                                         conv1 = dataConverters[ prev + " text" ] || dataConverters[ "* text" ];
445                                                                                         conv2 = dataConverters[ "text " + current ];
446                                                                                 }
447                                                                                 
448                                                                                 if ( oneConv || conv1 && conv2 ) {
449                                                                                         response = oneConv ? conv1( response ) : conv2( conv1( response ) );
450                                                                                 } else {
451                                                                                         throw "no " + conversion;
452                                                                                 }
453                                                                         }
454                                                                 }
455                                                         } else if ( s.dataFilter ) {
456                                                                 
457                                                                 response = s.dataFilter( response );
458                                                                 dataTypes = s.dataTypes;
459                                                         }
460                                                 }
461                 
462                                                 // We have a real success
463                                                 success = response;
464                                                 isSuccess = 1;
465                                                 
466                                         } catch(e) {
467                                                 
468                                                 statusText = "parsererror";
469                                                 error = "" + e;
470                                                 
471                                         }
472                                 }
473                                 
474                         } else { // if not success, mark it as an error
475                                 
476                                         error = error || statusText;
477                         }
478                                 
479                         // Set data for the fake xhr object
480                         jXHR.status = status;
481                         jXHR.statusText = statusText;
482                         
483                         // Success/Error
484                         if ( isSuccess ) {
485                                 deferred.fire( callbackContext , [ success , statusText , jXHR ] );
486                         } else {
487                                 deferred.fireReject( callbackContext , [ jXHR , statusText , error ] );
488                         }
489                         
490                         if ( s.global ) {
491                                 globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ) ,
492                                                 [ jXHR , s , isSuccess ? success : error ] );
493                         }
494                         
495                         // Complete
496                         completeDeferred.fire( callbackContext, [ jXHR , statusText ] );
497                         
498                         if ( s.global ) {
499                                 globalEventContext.trigger( "ajaxComplete" , [ jXHR , s] );
500                                 // Handle the global AJAX counter
501                                 if ( ! --jQuery.active ) {
502                                         jQuery.event.trigger( "ajaxStop" );
503                                 }
504                         }
505                 }
506                 
507                 // Attach deferreds     
508                 jXHR.success = jXHR.then = deferred.then;
509                 jXHR.error = jXHR.fail = deferred.fail;
510                 jXHR.complete = completeDeferred.then;
511
512                 // Remove hash character (#7531: and string promotion)
513                 s.url = ( "" + s.url ).replace( rhash , "" );
514                 
515                 // Uppercase the type
516                 s.type = s.type.toUpperCase();
517                 
518                 // Determine if request has content
519                 s.hasContent = ! rnoContent.test( s.type );
520                 
521                 // Extract dataTypes list
522                 s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( /\s+/ );
523                 
524                 // Determine if a cross-domain request is in order
525                 var parts = rurl.exec( s.url.toLowerCase() ),
526                         loc = location;
527                 s.crossDomain = !!( parts && ( parts[ 1 ] && parts[ 1 ] != loc.protocol || parts[ 2 ] != loc.host ) );
528
529                 // Convert data if not already a string
530                 if ( s.data && s.processData && typeof s.data != "string" ) {
531                         s.data = jQuery.param( s.data , s.traditional );
532                 }
533
534                 // Watch for a new set of requests
535                 if ( s.global && jQuery.active++ === 0 ) {
536                         jQuery.event.trigger( "ajaxStart" );
537                 }
538                 
539                 // Get transport
540                 transport = jQuery.ajax.prefilter( s ).transport( s );
541                 
542                 // If no transport, we auto-abort
543                 if ( ! transport ) {
544                         
545                         done( 0 , "transport not found" );
546                         jXHR = false;
547                         
548                 } else {
549                         
550                         // More options handling for requests with no content
551                         if ( ! s.hasContent ) {
552                                 
553                                 // If data is available, append data to url
554                                 if ( s.data ) {
555                                         s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
556                                 }
557                                                                 
558                                 // Add anti-cache in url if needed
559                                 if ( s.cache === false ) {
560                                         
561                                         var ts = jQuery.now(),
562                                                 // try replacing _= if it is there
563                                                 ret = s.url.replace( rts , "$1_=" + ts );
564                                                 
565                                         // if nothing was replaced, add timestamp to the end
566                                         s.url = ret + ( (ret == s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "");
567                                 }
568                         }
569                         
570                         // Set the correct header, if data is being sent
571                         if ( ( s.data && s.hasContent ) || options.contentType ) {
572                                 requestHeaders[ "content-type" ] = s.contentType;
573                         }
574                 
575                         // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
576                         if ( s.ifModified ) {
577                                 if ( jQuery_lastModified[ s.url ] ) { 
578                                         requestHeaders[ "if-modified-since" ] = jQuery_lastModified[ s.url ];
579                                 }
580                                 if ( jQuery_etag[ s.url ] ) {
581                                         requestHeaders[ "if-none-match" ] = jQuery_etag[ s.url ];
582                                 }
583                         }
584                 
585                         // Set the Accepts header for the server, depending on the dataType
586                         requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
587                                 s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
588                                 s.accepts[ "*" ];
589                                 
590                         // Check for headers option
591                         for ( i in s.headers ) {
592                                 requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
593                         }
594                         
595                         // Allow custom headers/mimetypes and early abort
596                         if ( s.beforeSend && ( s.beforeSend.call( callbackContext , jXHR , s ) === false || state === 2 ) ) {
597                                         
598                                         // Abort if not done already
599                                         done( 0 , "abort" );
600                                         jXHR = false;
601                                         
602                         } else {
603                                 
604                                 // Set state as sending
605                                 state = 1;
606                                 jXHR.readyState = 1;
607                                 
608                                 // Install callbacks on deferreds
609                                 for ( i in { success:1, error:1, complete:1 } ) {
610                                         jXHR[ i ]( s[ i ] );
611                                 }
612                                 
613                                 // Send global event
614                                 if ( s.global ) {
615                                         globalEventContext.trigger( "ajaxSend" , [ jXHR , s ] );
616                                 }
617                                 
618                                 // Timeout
619                                 if ( s.async && s.timeout > 0 ) {
620                                         timeoutTimer = setTimeout(function(){
621                                                 jXHR.abort( "timeout" );
622                                         }, s.timeout);
623                                 }
624                                 
625                                 // Try to send
626                                 try {
627                                         transport.send(requestHeaders, done);
628                                 } catch (e) {
629                                         // Propagate exception as error if not done
630                                         if ( status === 1 ) {
631
632                                                 done(0, "error", "" + e);
633                                                 jXHR = false;
634                                                 
635                                         // Simply rethrow otherwise
636                                         } else {
637                                                 jQuery.error(e);
638                                         }
639                                 }
640                         }
641                 }
642                 
643                 return jXHR;
644         },
645
646         // Serialize an array of form elements or a set of
647         // key/values into a query string
648         param: function( a, traditional ) {
649                 var s = [],
650                         add = function( key, value ) {
651                                 // If value is a function, invoke it and return its value
652                                 value = jQuery.isFunction(value) ? value() : value;
653                                 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
654                         };
655                 
656                 // Set traditional to true for jQuery <= 1.3.2 behavior.
657                 if ( traditional === undefined ) {
658                         traditional = jQuery.ajaxSettings.traditional;
659                 }
660                 
661                 // If an array was passed in, assume that it is an array of form elements.
662                 if ( jQuery.isArray(a) || a.jquery ) {
663                         // Serialize the form elements
664                         jQuery.each( a, function() {
665                                 add( this.name, this.value );
666                         });
667                         
668                 } else {
669                         // If traditional, encode the "old" way (the way 1.3.2 or older
670                         // did it), otherwise encode params recursively.
671                         for ( var prefix in a ) {
672                                 buildParams( prefix, a[prefix], traditional, add );
673                         }
674                 }
675
676                 // Return the resulting serialization
677                 return s.join("&").replace(r20, "+");
678         }
679 });
680
681 function buildParams( prefix, obj, traditional, add ) {
682         if ( jQuery.isArray(obj) && obj.length ) {
683                 // Serialize array item.
684                 jQuery.each( obj, function( i, v ) {
685                         if ( traditional || rbracket.test( prefix ) ) {
686                                 // Treat each array item as a scalar.
687                                 add( prefix, v );
688
689                         } else {
690                                 // If array item is non-scalar (array or object), encode its
691                                 // numeric index to resolve deserialization ambiguity issues.
692                                 // Note that rack (as of 1.0.0) can't currently deserialize
693                                 // nested arrays properly, and attempting to do so may cause
694                                 // a server error. Possible fixes are to modify rack's
695                                 // deserialization algorithm or to provide an option or flag
696                                 // to force array serialization to be shallow.
697                                 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
698                         }
699                 });
700                         
701         } else if ( !traditional && obj != null && typeof obj === "object" ) {
702                 // If we see an array here, it is empty and should be treated as an empty
703                 // object
704                 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
705                         add( prefix, "" );
706
707                 // Serialize object item.
708                 } else {
709                         jQuery.each( obj, function( k, v ) {
710                                 buildParams( prefix + "[" + k + "]", v, traditional, add );
711                         });
712                 }
713                                         
714         } else {
715                 // Serialize scalar item.
716                 add( prefix, obj );
717         }
718 }
719
720 // This is still on the jQuery object... for now
721 // Want to move this to jQuery.ajax some day
722 jQuery.extend({
723
724         // Counter for holding the number of active queries
725         active: 0,
726
727         // Last-Modified header cache for next request
728         lastModified: {},
729         etag: {}
730
731 });
732
733 //Execute or select from functions in a given structure of options
734 function ajax_selectOrExecute( structure , s ) {
735
736         var dataTypes = s.dataTypes,
737                 transportDataType,
738                 list,
739                 selected,
740                 i,
741                 length,
742                 checked = {},
743                 flag,
744                 noSelect = structure !== "transports";
745                 
746         function initSearch( dataType ) {
747
748                 flag = transportDataType !== dataType && ! checked[ dataType ];
749                 
750                 if ( flag ) {
751                         
752                         checked[ dataType ] = 1;
753                         transportDataType = dataType;
754                         list = s[ structure ][ dataType ];
755                         i = -1;
756                         length = list ? list.length : 0 ;
757                 }
758
759                 return flag;
760         }
761         
762         initSearch( dataTypes[ 0 ] );
763
764         for ( i = 0 ; ( noSelect || ! selected ) && i <= length ; i++ ) {
765                 
766                 if ( i === length ) {
767                         
768                         initSearch( "*" );
769                         
770                 } else {
771
772                         selected = list[ i ]( s , determineDataType );
773
774                         // If we got redirected to another dataType
775                         // Search there (if not in progress or already tried)
776                         if ( typeof( selected ) === "string" &&
777                                 initSearch( selected ) ) {
778
779                                 dataTypes.unshift( selected );
780                                 selected = 0;
781                         }
782                 }
783         }
784
785         return noSelect ? jQuery.ajax : selected;
786 }
787
788 // Add an element to one of the structures in ajaxSettings
789 function ajax_addElement( structure , args ) {
790                 
791         var i,
792                 start = 0,
793                 length = args.length,
794                 dataTypes = [ "*" ],
795                 dLength = 1,
796                 dataType,
797                 functors = [],
798                 first,
799                 append,
800                 list;
801                 
802         if ( length ) {
803                 
804                 first = jQuery.type( args[ 0 ] );
805                 
806                 if ( first === "object" ) {
807                         return ajax_selectOrExecute( structure , args[ 0 ] );
808                 }
809                 
810                 structure = jQuery.ajaxSettings[ structure ];
811                 
812                 if ( first !== "function" ) {
813                         
814                         dataTypes = args[ 0 ].toLowerCase().split(/\s+/);
815                         dLength = dataTypes.length;
816                         start = 1;
817                         
818                 }
819                 
820                 if ( dLength && start < length ) {
821                         
822                         functors = sliceFunc.call( args , start );
823                                         
824                         for( i = 0 ; i < dLength ; i++ ) {
825                                 
826                                 dataType = dataTypes[ i ];
827                                 
828                                 first = /^\+/.test( dataType );
829                                 
830                                 if (first) {
831                                         dataType = dataType.substr(1);
832                                 }
833                                 
834                                 if ( dataType !== "" ) {
835                                 
836                                         append = Array.prototype[ first ? "unshift" : "push" ];
837                                         list = structure[ dataType ] = structure[ dataType ] || [];
838                                         append.apply( list , functors );
839                                 }
840                         }
841                 }
842         }
843         
844         return jQuery.ajax;
845 }
846
847 // Install prefilter & transport methods
848 jQuery.each( [ "prefilter" , "transport" ] , function( _ , name ) {
849         _ = name + "s";
850         jQuery.ajax[ name ] = function() {
851                 return ajax_addElement( _ , arguments );
852         };
853 } );
854         
855 // Utility function that handles dataType when response is received
856 // (for those transports that can give text or xml responses)
857 function determineDataType( s , ct , text , xml ) {
858         
859         var autoDataType = s.autoDataType,
860                 type,
861                 regexp,
862                 dataTypes = s.dataTypes,
863                 transportDataType = dataTypes[0],
864                 response;
865         
866         // Auto (xml, json, script or text determined given headers)
867         if ( transportDataType === "*" ) {
868
869                 for ( type in autoDataType ) {
870                         if ( ( regexp = autoDataType[ type ] ) && regexp.test( ct ) ) {
871                                 transportDataType = dataTypes[0] = type;
872                                 break;
873                         }
874                 }                       
875         } 
876         
877         // xml and parsed as such
878         if ( transportDataType === "xml" &&
879                 xml &&
880                 xml.documentElement /* #4958 */ ) {
881                 
882                 response = xml;
883         
884         // Text response was provided
885         } else {
886                 
887                 response = text;
888                 
889                 // If it's not really text, defer to dataConverters
890                 if ( transportDataType !== "text" ) {
891                         dataTypes.unshift( "text" );
892                 }
893                 
894         }
895         
896         return response;
897 }       
898
899 /*
900  * Create the request object; Microsoft failed to properly
901  * implement the XMLHttpRequest in IE7 (can't request local files),
902  * so we use the ActiveXObject when it is available
903  * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
904  * we need a fallback.
905  */
906 if ( window.ActiveXObject ) {
907         jQuery.ajaxSettings.xhr = function() {
908         if ( window.location.protocol !== "file:" ) {
909                 try {
910                         return new window.XMLHttpRequest();
911                 } catch( xhrError ) {}
912         }
913         
914         try {
915                 return new window.ActiveXObject("Microsoft.XMLHTTP");
916         } catch( activeError ) {}
917         };
918 }
919
920 var testXHR = jQuery.ajaxSettings.xhr();
921
922 // Does this browser support XHR requests?
923 jQuery.support.ajax = !!testXHR;
924
925 // Does this browser support crossDomain XHR requests
926 jQuery.support.cors = testXHR && "withCredentials" in testXHR;
927
928 })( jQuery );