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