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