说说ajax的实现原理
# 是什么
ajax: async javascript and xml, 是一种在不重新加载网页的情况下,获取服务器数据的方式
# 原理
- 通过创建 XMLHttpRequest 对象向服务器发起异步请求,并获得服务器数据, 然后用 js 来操作 dom 更新页面
# 关键信息
- xhr
- open
- send
- onreadystatechange
- readyState
- status
- responseText
function ajax(option) {
const { url, type = "get", data, dataType = "json" } = option;
const xhr = new XMLHttpRequest();
if (type === "get") {
xhr.open(type, url + "?" + data, true);
xhr.send(null);
} else {
xhr.open(type, url, true);
xhr.send(data);
}
xhr.onreadystatechange = function(res) {
const status = res.status;
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(xhr.responseText);
} else if (xhr.status > 400) {
console.log("错误");
}
}
};
}
# FAQ
上次更新: 2021/12/19, 18:05:42