forked from ntzyz/playground
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsrc.js
72 lines (59 loc) · 1.7 KB
/
src.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
'use strict';
(function() {
function common(method, url, data, options) {
return new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest();
options = options || {};
xhr.open(method, url);
if (/POST|PUT/i.test(method)) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
if (data && typeof data === 'object') {
let pairs = [];
if (data instanceof FormData) {
for(let pair of data.entries()) {
pairs.push(encodeURIComponent(pair[0]) + '=' + encodeURIComponent(pair[1]));
}
}
else {
for(let key in data) {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
}
console.log(pairs);
data = pairs.join('&');
}
if (options.before) {
options.before(xhr);
}
xhr.onreadystatechange = function() {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
resolve(xhr);
}
else {
reject(xhr);
}
}
};
xhr.send(data);
});
}
let request = {};
request.get = function(url, options) {
return common('GET', url, undefined, options);
}
request.post = function(url, data, options) {
return common('POST', url, data, options);
}
request.put = function(url, data, options) {
return common('PUT', url, data, options);
}
request.delete = function(url, options) {
return common('DELETE', url, undefined, options);
}
request.head = function(url, options) {
return common('HEAD', url, undefined, options);
}
window.request = request;
})();