Repository navigation
Expand file tree
/
Copy pathajax.js
More file actions
73 lines (66 loc) · 1.7 KB
/
Copy pathajax.js
File metadata and controls
73 lines (66 loc) · 1.7 KB
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
function ajax(options) {
let { type, url, data, headers, beforeSend } = options;
type = type.toUpperCase() || 'GET';
let xhr = null, postData = null;
let asyn = options.async || true;
let before = false;
let timeStmp = new Date().getTime();
function createXHR() {
var xhr = null;
try {
xhr = new XMLHttpRequest();
} catch (tryMS) {
try {
xhr = new ActiveXObject('Msxm12.XMLHTTP');
} catch (otherMS) {
try {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
} catch (failed) {
xhr = null;
}
}
}
return xhr;
}
xhr = createXHR();
let arr = [];
if (data && _.isObject(data)) {
for (let key in data) {
if (data.hasOwnProperty(key)) {
var postStr = '' + key + '=' + data[key];
arr.push(postStr);
}
}
postData = arr.join('&');
type === 'GET' ? url = url + '?' + postData + '&t=' + timeStmp : url;
} else {
url = url + '?t=' + timeStmp;
}
return new Promise(function(resolve, reject) {
xhr.open(type, url, asyn);
if (headers) {
for (let header in headers) {
xhr.setRequestHeader(header, headers[header]);
}
}
if (type === 'GET') {
xhr.send();
} else {
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(postData);
}
xhr.onreadystatechange = function() {
if (typeof beforeSend === 'function' && before === false) {
beforeSend();
before = true;
}
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.responseText);
} else {
reject(xhr.status);
}
}
};
});
}