1
- /* jshint browser: true */
2
1
/* global exports */
2
+ /* global XMLHttpRequest */
3
+ /* global require */
4
+ /* global module */
3
5
"use strict" ;
4
6
5
7
// module Network.HTTP.Affjax
6
8
7
9
// jshint maxparams: 5
8
10
exports . _ajax = function ( mkHeader , options , canceler , errback , callback ) {
11
+ var platformSpecific = { } ;
12
+ if ( typeof module !== "undefined" && module . exports ) {
13
+ // We are on node.js
14
+ platformSpecific . newXHR = function ( ) {
15
+ var XHR = require ( "xmlhttprequest" ) . XMLHttpRequest ;
16
+ return new XHR ( ) ;
17
+ } ;
18
+
19
+ platformSpecific . fixupUrl = function ( url ) {
20
+ var urllib = require ( "url" ) ;
21
+ var u = urllib . parse ( url ) ;
22
+ u . protocol = u . protocol || "http:" ;
23
+ u . hostname = u . hostname || "localhost" ;
24
+ return urllib . format ( u ) ;
25
+ } ;
26
+
27
+ platformSpecific . getResponse = function ( xhr ) {
28
+ // the node package 'xmlhttprequest' does not support xhr.response.
29
+ return xhr . responseText ;
30
+ } ;
31
+ } else {
32
+ // We are in the browser
33
+ platformSpecific . newXHR = function ( ) {
34
+ return new XMLHttpRequest ( ) ;
35
+ } ;
36
+
37
+ platformSpecific . fixupUrl = function ( url ) {
38
+ return url || "/" ;
39
+ } ;
40
+
41
+ platformSpecific . getResponse = function ( xhr ) {
42
+ return xhr . response ;
43
+ } ;
44
+ }
45
+
9
46
return function ( ) {
10
- var xhr = new XMLHttpRequest ( ) ;
11
- xhr . open ( options . method || "GET" , options . url || "/" , true , options . username , options . password ) ;
47
+ var xhr = platformSpecific . newXHR ( ) ;
48
+ var fixedUrl = platformSpecific . fixupUrl ( options . url ) ;
49
+ xhr . open ( options . method || "GET" , fixedUrl , true , options . username , options . password ) ;
12
50
if ( options . headers ) {
13
51
for ( var i = 0 , header ; ( header = options . headers [ i ] ) != null ; i ++ ) {
14
52
xhr . setRequestHeader ( header . field , header . value ) ;
@@ -28,7 +66,7 @@ exports._ajax = function (mkHeader, options, canceler, errback, callback) {
28
66
var i = header . indexOf ( ":" ) ;
29
67
return mkHeader ( header . substring ( 0 , i ) ) ( header . substring ( i + 2 ) ) ;
30
68
} ) ,
31
- response : xhr . response
69
+ response : platformSpecific . getResponse ( xhr )
32
70
} ) ( ) ;
33
71
} ;
34
72
xhr . responseType = options . responseType ;
0 commit comments