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