-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathXHR.js
242 lines (179 loc) · 6.46 KB
/
XHR.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
(function (undefined) {
'use strict';
var global = typeof window === 'object' ? window : this;
var getXHR = global.ActiveXObject ? function () {
return new global.ActiveXObject('Microsoft.XMLHTTP');
} : global.XMLHttpRequest ? function () {
return new global.XMLHttpRequest();
} : function () {
throw 'Context does not support AJAX requests';
};
var parseJSON = global.JSON ? function (string) {
return global.JSON.parse(string);
} : function (string) {
return global.eval('(' + string + ')');
};
var parseXML = global.DOMParser ? function (string) {
return new global.DOMParser().parseFromString(string, 'text/xml');
} : global.ActiveXObject ? function (string) {
var doc = new global.ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(string);
return doc;
} : function (string) {
throw 'Context does not support XML parsing';
};
// Polyfill https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill
if (!global.String.prototype.trim) {
global.String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
// Polyfill https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Date/now#Proth%C3%A8se_d'%C3%A9mulation_(polyfill)
if (!global.Date.now) {
global.Date.now = function () {
return new global.Date().getTime();
};
}
function each (object, callback) {
for (var i in object)
if (object.hasOwnProperty(i))
if (callback(i, object[i]) === false)
break;
}
function extend (original, by) {
var object = {};
each(original, function (key, value) {
object[key] = value;
});
each(by, function (key, value) {
object[key] = value;
});
return object;
}
function clone (object) {
return extend({}, object);
}
function endPromise (xhr, params, resolve, reject) {
((200 <= xhr.status && xhr.status <= 206) || xhr.status === 304 ? resolve : reject)( digestXHR(xhr, params) );
}
function digestResponse (responseText, headers, params) {
var type = params.responseType;
if (type === 'auto') {
if (headers['Content-Type']) {
var ref = {
'json': /^(?:text|application)\/json(?:;.+)?$/,
'xml': /^(?:text|application)\/xml(?:;.+)?$/
};
each(ref, function (key, regex) {
if (regex.test(headers['Content-Type'])) {
type = key;
return false;
}
});
// If no matching on Content-Type has been found
if (type === 'auto') type = 'text';
}
else type = 'text';
}
// Then we are sure to have an explicit value as type
return type === 'json' ? parseJSON(responseText) :
type === 'xml' ? parseXML(responseText) :
responseText;
}
function digestHeaders (rawHeaders) {
rawHeaders = rawHeaders.split(/\r\n/);
var headers = {};
for (var i = 0; i < rawHeaders.length; i++) {
var sepIndex = rawHeaders[i].indexOf(':');
if (sepIndex !== -1) { // Avoid empty item or incorrect item at the end of the split
var headerName = rawHeaders[i]
.substring(0, sepIndex)
.trim()
.replace(/(^.)|(-.)/g, function ($0, $1, $2) {
return ($1 || $2).toUpperCase();
});
var headerValue = rawHeaders[i]
.substring(sepIndex + 1)
.trim();
headers[ headerName ] = headerValue;
}
}
return headers;
}
function digestXHR (xhr, params) {
var headers = digestHeaders(xhr.getAllResponseHeaders());
var response = digestResponse(xhr.responseText, headers, params);
return {
status: xhr.status,
responseText: xhr.responseText,
response: response,
responseHeaders: headers
};
}
function XHR (params) {
params = extend(XHR.defaultParams, params);
// Avoid altering external references
params.headers = clone(params.headers);
if (!params.headers['Content-Type'])
params.headers['Content-Type'] = params.contentType;
if (!params.cache) {
// Avoid storing response along the network
params.headers['Cache-Control'] = 'no-cache, no-store';
// Trick browser to force it not to use its cache
var nocache = '';
do { nocache += '_'; }
while (new global.RegExp('[?&]' + nocache + '=').test(params.url));
params.url += (params.url.indexOf('?') !== -1 ? '&' : '?') + nocache + '=' + global.Date.now();
}
// Serialize data if provided as object
if (typeof params.data === 'object'){
var data = [];
each(params.data, function (name, value) {
data.push(global.encodeURIComponent(name) + '=' + global.encodeURIComponent(value));
});
params.data = data.join('&');
}
return Promise.exec(function (resolve, reject, notify) {
var xhr = getXHR();
// Bind listener before calling xhr.open since IE prevents it to be set after the call
if (params.async)
xhr.onreadystatechange = function () {
notify(xhr.readyState);
if (xhr.readyState === 4)
endPromise(xhr, params, resolve, reject);
};
xhr.open(params.method, params.url, params.async, params.user, params.password);
each(params.headers, function (name, value) {
xhr.setRequestHeader(name, value);
});
xhr.send(params.data);
// Synchronous mode
if (!params.async)
endPromise(xhr, params, resolve, reject);
});
}
XHR.defaultParams = {
url: undefined,
// GET, POST, HEAD, PUT, DELETE etc..
method: 'GET',
user: undefined,
password: undefined,
// 'auto' : response is parsed according to the Content-Type response header or text if no header
// 'text' : no parsing is done
// 'json' : response is parsed as a JSON string
// 'xml' : response is parsed as DOM string
responseType: 'auto',
async: true,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
headers: {},
data: null,
// false: force always asking to the server (appending a random seed in the URL) + do not store response in cache
cache: true
};
XHR.noConflict = function () {
global.XHR = XHR.conflicted;
return XHR;
};
XHR.conflicted = global.XHR;
global.XHR = XHR;
})();