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