如何手动封装一个ajax请求,用函数方式调用即可?
废话不多说,直接上代码
<script>
function MyAjax(params) {
let xhr = new XMLHttpRequest();
//将传递过来的method 转换为大写 转小写也可以,为了后面的if判断条件
params.method = params.method.toUpperCase();
if (params.method === "GET") {
xhr.open(params.method, params.url);
xhr.send();
}
if (params.method === "POST") {
xhr.open(params.method, params.url, params.data);
xhr.setRequestHeader(
"Content-Type",
"application/x-wwww-form-urlencoded"
);
xhr.send();
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// 定义一个变量 接收服务器返回来的数据 并用JOSN.parse转换为对象
let res = JSON.parse(xhr.responseText);
//打印看看服务器返回来的数据
console.log(res);
}
};
}
//直接调用MyAjax 里面传递你要发送的get/post请求及参数
MyAjax({
method: "GET",
url: "http://www.xxxx",
});
</script>
简易的封装发送get/post请求,技术交流,轻喷~