e21847aa8eaea7cee03fe14b2141076a4a5fca75
[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                                         // Override mime type if needed
91                                         if ( s.mimeType && xhr.overrideMimeType ) {
92                                                 xhr.overrideMimeType( s.mimeType );
93                                         }
94
95                                         // Requested-With header
96                                         // Not set for crossDomain requests with no content
97                                         // (see why at http://trac.dojotoolkit.org/ticket/9486)
98                                         // Won't change header if already provided
99                                         if ( !( s.crossDomain && !s.hasContent ) && !headers["X-Requested-With"] ) {
100                                                 headers[ "X-Requested-With" ] = "XMLHttpRequest";
101                                         }
102
103                                         // Need an extra try/catch for cross domain requests in Firefox 3
104                                         try {
105                                                 for ( i in headers ) {
106                                                         xhr.setRequestHeader( i, headers[ i ] );
107                                                 }
108                                         } catch( _ ) {}
109
110                                         // Do send the request
111                                         // This may raise an exception which is actually
112                                         // handled in jQuery.ajax (so no try/catch here)
113                                         xhr.send( ( s.hasContent && s.data ) || null );
114
115                                         // Listener
116                                         callback = function( _, isAbort ) {
117
118                                                 var status,
119                                                         statusText,
120                                                         responseHeaders,
121                                                         responses,
122                                                         xml;
123
124                                                 // Firefox throws exceptions when accessing properties
125                                                 // of an xhr when a network error occured
126                                                 // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
127                                                 try {
128
129                                                         // Was never called and is aborted or complete
130                                                         if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
131
132                                                                 // Only called once
133                                                                 callback = undefined;
134
135                                                                 // Do not keep as active anymore
136                                                                 if ( handle ) {
137                                                                         xhr.onreadystatechange = jQuery.noop;
138                                                                         delete xhrCallbacks[ handle ];
139                                                                 }
140
141                                                                 // If it's an abort
142                                                                 if ( isAbort ) {
143                                                                         // Abort it manually if needed
144                                                                         if ( xhr.readyState !== 4 ) {
145                                                                                 xhr.abort();
146                                                                         }
147                                                                 } else {
148                                                                         status = xhr.status;
149                                                                         responseHeaders = xhr.getAllResponseHeaders();
150                                                                         responses = {};
151                                                                         xml = xhr.responseXML;
152
153                                                                         // Construct response list
154                                                                         if ( xml && xml.documentElement /* #4958 */ ) {
155                                                                                 responses.xml = xml;
156                                                                         }
157                                                                         responses.text = xhr.responseText;
158
159                                                                         // Firefox throws an exception when accessing
160                                                                         // statusText for faulty cross-domain requests
161                                                                         try {
162                                                                                 statusText = xhr.statusText;
163                                                                         } catch( e ) {
164                                                                                 // We normalize with Webkit giving an empty statusText
165                                                                                 statusText = "";
166                                                                         }
167
168                                                                         // Filter status for non standard behaviors
169                                                                         status =
170                                                                                 // If the request is local and we have data: assume a success
171                                                                                 // (success with no data won't get notified, that's the best we
172                                                                                 // can do given current implementations)
173                                                                                 !status && s.isLocal ?
174                                                                                 ( responses.text ? 200 : 404 ) :
175                                                                                 // IE - #1450: sometimes returns 1223 when it should be 204
176                                                                                 ( status === 1223 ? 204 : status );
177                                                                 }
178                                                         }
179                                                 } catch( firefoxAccessException ) {
180                                                         if ( !isAbort ) {
181                                                                 complete( -1, firefoxAccessException );
182                                                         }
183                                                 }
184
185                                                 // Call complete if needed
186                                                 if ( responses ) {
187                                                         complete( status, statusText, responses, responseHeaders );
188                                                 }
189                                         };
190
191                                         // if we're in sync mode or it's in cache
192                                         // and has been retrieved directly (IE6 & IE7)
193                                         // we need to manually fire the callback
194                                         if ( !s.async || xhr.readyState === 4 ) {
195                                                 callback();
196                                         } else {
197                                                 // Create the active xhrs callbacks list if needed
198                                                 // and attach the unload handler
199                                                 if ( !xhrCallbacks ) {
200                                                         xhrCallbacks = {};
201                                                         xhrOnUnloadAbort();
202                                                 }
203                                                 // Add to list of active xhrs callbacks
204                                                 handle = xhrId++;
205                                                 xhr.onreadystatechange = xhrCallbacks[ handle ] = callback;
206                                         }
207                                 },
208
209                                 abort: function() {
210                                         if ( callback ) {
211                                                 callback(0,1);
212                                         }
213                                 }
214                         };
215                 }
216         });
217 }
218
219 })( jQuery );