封装ajax函数 && 实现一个axios
mtonhuang opened this issue · comments
基础——XHR用法
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
//xhr.readyState == 4时,表示所有数据已经准备就绪
if (xhr.readyState == 4) {
//status 为200时表示成功,304则表示资源没有被修改,继续使用缓存
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
console.log(xhr.responseText)
} else {
console.log(xhr.status)
}
}
};
xhr.open('get', 'test.txt', true);
xhr.send(null)
基于原生js封装简易的ajax函数
let ejax = {
get: function(url, fn, async) {
let xhr = new XMLHttpRequest();
xhr.open(url, "GET");
xhr.onreadystatechange = () => {
if ((xhr.readyState == 4 && xhr.status == 200) || xhr.status == 304) {
let result = xhr.responseText;
fn.call(this, result);
}
};
xhr.send();
},
post: function(url, fn, async) {
let xhr = new XMLHttpRequest();
xhr.open(url, "POST", async);
xhr.setRequestHeader(
"conten-type",
"application/x-www-form-urlencoded"
);
xhr.onreadystatechange = () => {
if (
(xhr.readyState === 4 && xhr.status == 200) ||
xhr.status == 304
) {
let result = xhr.responseText;
fn.call(this, result);
}
};
xhr.send(data);
}
};
基于Promise实现一个简易的axios
let exios = function({
url = null,
method = "GET",
dataType = "JSON",
async = true,
}) {
let promiseApi = new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open(method, url, async);
xhr.responseType = dataType;
xhr.onreadystatechange = () => {
if (!/^[23]\d{2}$/.test(xhr.status)) return;
if (xhr.readyState === 4) {
let result = xhr.responseText;
resolve(result);
}
};
xhr.onerror = (err) => {
reject(err);
};
xhr.send();
});
return promiseApi;
};
}