脚本宝典收集整理的这篇文章主要介绍了用ES6封装AJAX函数,支持GET/POST,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
function Ajax({
type = "GET",
url = "",
async = true,
params = {},
responseType = "text",
contentType = "application/x-www-form-urlencoded", //xhr.setRequestHeader("Content-type",option.contentType);
done = () => {},
fail = () => {}
}) {
type = type.toUpperCase();
params = formatParams(params);
//创建xhr对象 step1
const xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
xhr.responseType = responseType;
//接收 step3
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
const status = xhr.status;
if (status >= 200 && status < 300) {
done(response);
} else {
fail(status);
}
}
}
//发送 step2
if (type === "GET") {
xhr.open("GET", url + "?" + params, async);
xhr.send(null);
} else if (type === "POST") {
xhr.open("POST", url, async);
//设置表单提交时的内容类型
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(params);
}
}
function formatParams(params) {
const arr = [];
for (let name in params) {
arr.push(encodeURIcomponent(name) + "=" + encodeURIComponent(params[name]));
}
arr.push(("_=" + Math.random()).replace(".", ""));
return arr.join("&");
}
以上是脚本宝典为你收集整理的用ES6封装AJAX函数,支持GET/POST全部内容,希望文章能够帮你解决用ES6封装AJAX函数,支持GET/POST所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。