/**封装网络请求 */
/**baseUrl */
var baseUrl = ''; //此处填写您的域名地址
/**token */
const token = sessionStorage.getItem("token"); //获取存储在浏览器中的token
let headers;
if(token){
headers = {
"Authorization": token //关于请求头
}
}
/**get请求数据 */
function getData (url = '', params = {}, isLoading = false) {
if(isLoading){
layer.load(1) //在请求未响应之前,给用户一个等待状态
}
var promise = new Promise((resolve, reject)=>{
$.ajax({
url: baseUrl + url,
type: 'GET',
data: params,
headers,
success: res=>{
if(isLoading){
layer.closeAll('loading')
}
if(res.code == 200){
resolve(res.data)
}else if(res.code == 404){
layer.msg(res.msg, {icon: 7})
reject(res.data)
}else if(res.code == 401){
layer.msg('登录过期,请重新登录', {icon: 7})
setTimeout(() => {
sessionStorage.clear();
window.location.href = '../page/login.html' //根据后端返回code,判断一些错误情况
}, 1500);
}else if(res.code == 403){
layer.msg('您无权限访问此系统', {icon: 7})
setTimeout(() => {
sessionStorage.clear();
window.location.href = '../page/login.html'
}, 1500);
}
},
error: err=>{
layer.msg(err, {icon: 7}) //其他错误情况
reject(err)
}
})
})
return promise
}
/**post请求数据 */
function postData (url = '', params = {}, isLoading = false) {
if(isLoading){
layer.load(1)
}
var promise = new Promise((resolve, reject)=>{
$.ajax({
url: baseUrl + url,
type: 'POST',
data: params,
headers,
success: res=>{
if(isLoading){
layer.closeAll('loading')
}
if(res.code == 200){
resolve(res.data)
}else if(res.code == 404){
layer.msg(res.msg, {icon: 7})
reject(res.data)
}else if(res.code == 401){
layer.msg('登录过期,请重新登录', {icon: 7})
setTimeout(() => {
sessionStorage.removeItem('token')
window.location.href = 'page/login.html'
}, 1500);
}else if(res.code == 403){
layer.msg('您无权限访问此系统', {icon: 7})
setTimeout(() => {
sessionStorage.removeItem('token')
window.location.href = 'page/login.html'
}, 1500);
}
},
error: err=>{
layer.msg(err, {icon: 7})
reject(err)
}
})
})
return promise
}
为方便在layui后台管理中提升开发效率,所以在js中封装了方法,以方便使用。