Makes sure xhrs are actually aborted on unload in IE. Simplifies active xhrs caching...
[jquery.git] / src / ajax / xhr.js
1 (function( jQuery ) {
2
3 var // #5280: next active xhr id and list of active xhrs' callbacks
4         xhrId = jQuery.now(),
5         xhrCallbacks,
6
7         // XHR used to determine supports properties
8         testXHR;
9
10 // #5280: Internet Explorer will keep connections alive if we don't abort on unload
11 function xhrOnUnloadAbort() {
12         jQuery( window ).unload(function() {
13                 // Abort all pending requests
14                 for ( var key in xhrCallbacks ) {
15                         xhrCallbacks[ key ]( 0, 1 );
16                 }
17         });
18 }
19
20 // Functions to create xhrs
21 function createStandardXHR() {
22         try {
23                 return new window.XMLHttpRequest();
24         } catch( e ) {}
25 }
26
27 function createActiveXHR() {
28         try {
29                 return new window.ActiveXObject("Microsoft.XMLHTTP");
30         } catch( e ) {}
31 }
32
33 // Create the request object
34 // (This is still attached to ajaxSettings for backward compatibility)
35 jQuery.ajaxSettings.xhr = window.ActiveXObject ?
36         /* Microsoft failed to properly
37          * implement the XMLHttpRequest in IE7 (can't request local files),
38          * so we use the ActiveXObject when it is available
39          * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
40          * we need a fallback.
41          */
42         function() {
43                 return !this.isLocal && createStandardXHR() || createActiveXHR();
44         } :
45         // For all other browsers, use the standard XMLHttpRequest object
46         createStandardXHR;
47
48 // Test if we can create an xhr object
49 testXHR = jQuery.ajaxSettings.xhr();
50 jQuery.support.ajax = !!testXHR;
51
52 // Does this browser support crossDomain XHR requests
53 jQuery.support.cors = testXHR && ( "withCredentials" in testXHR );
54
55 // No need for the temporary xhr anymore
56 testXHR = undefined;
57
58 // Create transport if the browser can provide an xhr
59 if ( jQuery.support.ajax ) {
60
61         jQuery.ajaxTransport(function( s ) {
62                 // Cross domain only allowed if supported through XMLHttpRequest
63                 if ( !s.crossDomain || jQuery.support.cors ) {
64
65                         var callback;
66
67                         return {
68                                 send: function( headers, complete ) {
69
70                                         // Get a new xhr
71                                         var xhr = s.xhr(),
72                                                 handle,
73                                                 i;
74
75                                         // Open the socket
76                                         // Passing null username, generates a login popup on Opera (#2865)
77                                         if ( s.username ) {
78                                                 xhr.open( s.type, s.url, s.async, s.username, s.password );
79                                         } else {
80                                                 xhr.open( s.type, s.url, s.async );
81                                         }
82
83                                         // Apply custom fields if provided
84                                         if ( s.xhrFields ) {
85                                                 for ( i in s.xhrFields ) {
86                                                         xhr[ i ] = s.xhrFields[ i ];
87                                                 }
88                                         }
89
90                                         // Requested-With header
91                                         // Not set for crossDomain requests with no content
92                                         // (see why at http://trac.dojotoolkit.org/ticket/9486)
93                                         // Won't change header if already provided
94                                         if ( !( s.crossDomain && !s.hasContent ) && !headers["x-requested-with"] ) {
95                                                 headers[ "x-requested-with" ] = "XMLHttpRequest";
96                                         }
97
98                                         // Need an extra try/catch for cross domain requests in Firefox 3
99                                         try {
100                                                 jQuery.each( headers, function( key, value ) {
101                                                         xhr.setRequestHeader( key, value );
102                                                 } );
103                                         } catch( _ ) {}
104
105                                         // Do send the request
106                                         // This may raise an exception which is actually
107                                         // handled in jQuery.ajax (so no try/catch here)
108                                         xhr.send( ( s.hasContent && s.data ) || null );
109
110                                         // Listener
111                                         callback = function( _, isAbort ) {
112
113                                                 var status,
114                                                         statusText,
115                                                         responseHeaders,
116                                                         responses,
117                                                         xml;
118
119                                                 // Firefox throws exceptions when accessing properties
120                                                 // of an xhr when a network error occured
121                                                 // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
122                                                 try {
123
124                                                         // Was never called and is aborted or complete
125                                                         if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
126
127                                                                 // Only called once
128                                                                 callback = undefined;
129
130                                                                 // Do not keep as active anymore
131                                                                 if ( handle ) {
132                                                                         xhr.onreadystatechange = jQuery.noop;
133                                                                         delete xhrCallbacks[ handle ];
134                                                                 }
135
136                                                                 // If it's an abort
137                                                                 if ( isAbort ) {
138                                                                         // Abort it manually if needed
139                                                                         if ( xhr.readyState !== 4 ) {
140                                                                                 xhr.abort();
141                                                                         }
142                                                                 } else {
143                                                                         status = xhr.status;
144                                                                         responseHeaders = xhr.getAllResponseHeaders();
145                                                                         responses = {};
146                                                                         xml = xhr.responseXML;
147
148                                                                         // Construct response list
149                                                                         if ( xml && xml.documentElement /* #4958 */ ) {
150                                                                                 responses.xml = xml;
151                                                                         }
152                                                                         responses.text = xhr.responseText;
153
154                                                                         // Firefox throws an exception when accessing
155                                                                         // statusText for faulty cross-domain requests
156                                                                         try {
157                                                                                 statusText = xhr.statusText;
158                                                                         } catch( e ) {
159                                                                                 // We normalize with Webkit giving an empty statusText
160                                                                                 statusText = "";
161                                                                         }
162
163                                                                         // Filter status for non standard behaviors
164
165                                                                         // IE - #1450: sometimes returns 1223 when it should be 204
166                                                                         if ( status === 1223 ) {
167                                                                                 status = 204;
168                                                                         // Various - #8177: a Not Modified response was received
169                                                                         // yet no conditional request headers was provided
170                                                                         } else if ( status === 304 &&
171                                                                                                 !headers[ "if-modified-since" ] &&
172                                                                                                 !headers[ "if-none-match" ] ) {
173                                                                                 status = 200;
174                                                                         // Status 0 encompasses several cases
175                                                                         } else if ( !status ) {
176                                                                                 // Cross-domain
177                                                                                 if ( s.crossDomain ) {
178                                                                                         if ( !s.statusText ) {
179                                                                                                 // FF, Webkit (other?): There is no status text for errors
180                                                                                                 // 302 is the most generic cross-domain status code
181                                                                                                 // for errors, could be anything really (even a real 0)
182                                                                                                 status = 302;
183                                                                                         }
184                                                                                 // All same-domain: for local files, 0 is a success
185                                                                                 } else if( s.isLocal ) {
186                                                                                         status = 200;
187                                                                                         // Opera: this notifies success for all requests
188                                                                                         // (verified in 11.01). Patch welcome.
189                                                                                 }
190                                                                                 // Opera - #6060: sets status as 0 for 304
191                                                                                 // Patch welcome.
192                                                                         }
193                                                                 }
194                                                         }
195                                                 } catch( firefoxAccessException ) {
196                                                         if ( !isAbort ) {
197                                                                 complete( -1, firefoxAccessException );
198                                                         }
199                                                 }
200
201                                                 // Call complete if needed
202                                                 if ( responses ) {
203                                                         complete( status, statusText, responses, responseHeaders );
204                                                 }
205                                         };
206
207                                         // if we're in sync mode or it's in cache
208                                         // and has been retrieved directly (IE6 & IE7)
209                                         // we need to manually fire the callback
210                                         if ( !s.async || xhr.readyState === 4 ) {
211                                                 callback();
212                                         } else {
213                                                 // Create the active xhrs callbacks list if needed
214                                                 // and attach the unload handler
215                                                 if ( !xhrCallbacks ) {
216                                                         xhrCallbacks = {};
217                                                         xhrOnUnloadAbort();
218                                                 }
219                                                 // Add to list of active xhrs callbacks
220                                                 handle = xhrId++;
221                                                 xhr.onreadystatechange = xhrCallbacks[ handle ] = callback;
222                                         }
223                                 },
224
225                                 abort: function() {
226                                         if ( callback ) {
227                                                 callback(0,1);
228                                         }
229                                 }
230                         };
231                 }
232         });
233 }
234
235 })( jQuery );