-
Notifications
You must be signed in to change notification settings - Fork 2
/
ajax.js
84 lines (63 loc) · 2.36 KB
/
ajax.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
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
// https://developer.mozilla.org/en-US/docs/Web/API/FormData
// https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
function ajax(url, options) {
options.method = options.method || "GET";
options.async = options.async || true;
options.user = options.user || null;
options.password = options.password || null;
options.data = options.data || null;
options.responseType = options.responseType || "text";
let request = new XMLHttpRequest();
request.responseType = options.responseType;
request.open(options.method, url, options.async, options.user, options.password);
if (options.headers) {
for (let header in options.headers) {
let value = options.headers[header];
request.setRequestHeader(header, value);
}
}
if (options.start) {
request.onloadstart = options.start.bind(request);
}
if (options.progress) {
request.onprogress = function (e) {
options.progress.call(request, e);
};
}
if (options.uploadProgress) {
request.upload.onprogress = function (e) {
options.uploadProgress.call(request, e);
};
}
if (options.after) {
request.onloadend = function () {
options.after.call(this);
};
}
if (options.success || options.fail) {
request.onreadystatechange = function () {
if (request.readyState == XMLHttpRequest.DONE) {
if (request.status == 200) {
if (options.success)
options.success.call(this);
} else {
if (options.fail)
options.fail.call(this);
}
}
};
}
if (options.timeout) {
request.timeout = options.timeout;
}
if (options.data && !(options.data instanceof FormData)) {
let data = new FormData();
for (let key in options.data) {
data.append(key, options.data[key]);
}
options.data = data;
}
request.send(options.data);
return request;
}