如何手动封装一个ajax请求,用函数方式调用即可?
废话不多说,直接上代码
script
function MyAjax(params) {
let xhr = new XMLHttpRequest();
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) {
let res = JSON.parse(xhr.responseText);
console.log(res);
}
};
}
MyAjax({
method: "GET",
url: "http://www.xxxx",
});
/script
简易的封装发送get/post请求,技术交流,轻喷~