手写Ajax

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
  /**
* 手写一个简单的ajax
*
* @param {string} method - 请求方法
* @param {string} url - 请求地址
* @param {string} data - 请求参数
* @param {function} onSuccessCallback - 请求成功的毁掉
* @param {function} onErrorCallback - 失败的毁掉
*/
function sendAjaxRequest(method, url, data, onSuccessCallback, onErrorCallback) {
let xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
try {
const res = JSON.parse(xhr.responseText);
onSuccessCallback(res);
} catch (error) {
onErrorCallback(error);
}
} else {
onErrorCallback(`Error:${xhr.status}`);
}
}
};

if (method === "POST" && data) {
xhr.send(JSON.stringify(data));
} else {
xhr.send();
}
}