xhr简单封装ajax
// 设置默认值
const defaults = {
type: "get",
url: "",
async: true,
data: {},
header: {
"Content-Type": "application/x-www-form-urlencoded",
},
success: function () {},
error: function () {},
};
function dealParams(data) {
let params = "";
for (let k in data) {
params += k + "&" + data[k];
}
params = params.trim().lenth > 0 ? params.slice(0, params.length) : "";
}
const ajax = (options) => {
// 将传入的值替换默认值
Object.assign(defaults, options);
// 创建xhr对象
const xhr = new XMLHttpRequest();
// 1.get请求
if (defaults.type.toLocaleLowerCase() == "get") {
params = dealParams(defaults.data);
if (params) {
defaults.url = "?" + params;
}
defaults.data = null;
} else if (defaults.type.toLowerCase() == "post") {
// 2.post请求
xhr.setRequestHeader("Content-Type", defaults.header["Content-Type"]);
const contentType = defaults.header["Content-Type"];
if (contentType.includes("application/json")) {
defaults.data = JSON.stringify(defaults.data);
} else if (contentType.includes("application/x-www-form-urlencoded")) {
defaults.data = dealParams(defaults.data);
}
}
// 监听load事件,和readystatechange
try {
xhr.addEventListener("load", () => {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
defaults.success(xhr.responseText, xhr);
} else {
defaults.error(xhr.responseText, xhr);
}
});
} catch (err) {
defaults.error(err, xhr);
}
xhr.addEventListener("error", () => {
defaults.error(xhr);
});
xhr.open(defaults.type, defaults.url, defaults.async);
xhr.send(defaults.data);
};