-
Notifications
You must be signed in to change notification settings - Fork 134
/
Copy pathxhr.js
51 lines (47 loc) · 1.41 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
import queryString from 'query-string';
/*
* Simple AJAX request object
*/
var Request = function (url, data, headers) {
this.url = url;
this.data = data || {};
this.headers = headers;
};
function setHeaders(xhr, headers) {
for (const header in headers) {
xhr.setRequestHeader(header, headers[header]);
}
}
Request.prototype.send = function (callback) {
var isIE = window.XDomainRequest ? true : false;
if (isIE) {
var xdr = new window.XDomainRequest();
xdr.open('POST', this.url, true);
xdr.onload = function () {
callback(200, xdr.responseText);
};
xdr.onerror = function () {
// status code not available from xdr, try string matching on responseText
if (xdr.responseText === 'Request Entity Too Large') {
callback(413, xdr.responseText);
} else {
callback(500, xdr.responseText);
}
};
xdr.ontimeout = function () {};
xdr.onprogress = function () {};
xdr.send(queryString.stringify(this.data));
} else {
var xhr = new XMLHttpRequest();
xhr.open('POST', this.url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
callback(xhr.status, xhr.responseText);
}
};
setHeaders(xhr, this.headers);
xhr.send(queryString.stringify(this.data));
}
//log('sent request to ' + this.url + ' with data ' + decodeURIComponent(queryString(this.data)));
};
export default Request;