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