Ajax封装
function ajax (type , url , data , callback) {
// 兼容IE
const xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
// 判断传参类型
if(typeof data === 'object') {
let str = "";
for(let key in data) {
str+=`${key}=${data[key]}&`; // 将对象形式转换成 name=cht&age=18&
}
data = str.slice(0);
}
type = type.toUpperCase();
if(type === "GET") {
if(data) {
// 传参情况
xhr.open("GET" , `${url}?${data}` , true); // 拼接URL ?name=cht&age=18&
}else {
// 无参情况
xhr.open("GET" , url , true);
}
xhr.send(null);
}else if(type === "POST") {
xhr.open("POST" , url , true) ;
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); // post请求需要设置请求头
if(data) {
xhr.send(data);
}else {
xhr.send(null);
}
}else {
return "error";
}
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) {
const res = xhr.responseText;
callback(res);
}
}
}
← Ajax入门