原生JS:封装ajax
每次调用ajax都需要写核心代码,为了减少代码冗余提高代码复用率,对ajax进行封装,方便使用
以下是ajax的核心代码:
//挖洞 修地铁 => 创建ajax对象
var xhr = new XMLHttpRequest();
// 开通地铁 确定站名 => 确定请求
xhr.open('get', './a.txt', true); //默认开启异步,所有这里的true可以不写
// 买票上车
xhr.send();
// 监听站名 到特定站下车
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 && xhr.status ==200){
console.log(xhr.responseText); // 获取请求到的内容
}
}
封装之后的代码:
// 封装ajax函数 v1
function ajax({ path, success, data = {}, method = 'get' }) {
// 处理data对象
var params = '';
for (var key in data) {
params += `${key}=${data[key]}&`;
}
params = params.substring(0, params.length - 1);
var xhr = new XMLHttpRequest();
if (method.toLowerCase() == 'post') {
xhr.open(method, path);
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
xhr.send(params);
} else {
xhr.open(method, `${path}?${params}`);
xhr.send();
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = xhr.responseText;
try {
data = JSON.parse(data);
} catch (e) {
console.log(e);
}
success && success(data);
}
}
}
以下是上述封装的提升,简化调用,前提是基于上述代码的封装:
// request封装,ajax升级 v2
const request = (path, data, method = 'get') => {
return new Promise(resolve => {
ajax({
path,
data,
method,
success: res => resolve(res)
// success:resolve
})
})
}
// API封装,ajax升级 v3
const apiUserRegister = data => request('http://localhost/day21_11_16/register.php', data);
const apiUserLogin = data => request('http://localhost/day21_11_16/login.php', data);
const apiUserList = data => request('http://localhost/day22_11_17/list.php', data);
const apiUserDelete = data => request('http://localhost/day22_11_17/delete.php', data);
const apiUserUpdate = data => request('http://localhost/day22_11_17/update.php', data);
使用:
v1:版本一的使用
ajax({
path:'http://localhost/day22_11_17/list.php',
success:function ({ data }) {
var html = data.reduce((total, item) => {
return total += `
<p>${item.username}</p>
`;
}, '');
document.body.innerHTML = html;
},
data:{
a:10,
b:20
}
// method:'post'
});
v3:版本三的使用
apiUserLogin({
username,
password
}).then(({ code, msg }) => {
if (code) {
layer.msg('登录成功');
localStorage.setItem('username', username);
location.href = url || '/vancl/index.html';
} else {
layer.msg(msg);
}
})