手写Ajax

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const ajax = (method, url, data, success, fail) => {
var request = new XMLHttpRequest();
request.open(method, url); //这里默认用异步请求
request.onreadystatechange = function () {
if (request.readyState === 4) {
if ((request.status >= 200 && request.status < 300) || request.status === 304) {
success(request);
} else {
fail(request);
}
}
};
request.send();
};

补充一个Promise版本的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const getJSON = function (url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;
if (xhr.status === 200 || xhr.status === 304) {
resolve(xhr.responseText);
} else {
reject(new Error(xhr.responseText));
}
};
xhr.send();
});
};


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!