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