有时候我们想通过ajax访问接口,但又感觉每一次都要去判断一遍ajax的前置动作(在头里放入token,开启加载动画等)和后置动作(判断token是否超时自动刷新,关闭加载动画等)很是啰嗦,这时候我们可以通过封装ajax省略这些没必要的代码。
layui.define(['layer', 'jquery'], function (exports) {
"use strict";
let MOD_NAME = "flyio";
let layer = layui.layer;
let $ = layui.jquery;
let config = {
headers: {}, //http请求头,可以放入token等等
baseURL: "", //请求基地址
timeout: 3000,//超时时间,为0时则无超时限制
};
let flyio = new function () {
this.get = function (url, params) {
return ajax("GET", url, params);
};
this.post = function (url, params) {
return ajax("POST", url, JSON.stringify(params));
};
this.delete = function (url, params) {
return ajax("DELETE", url, params);
}
this.put = function (url, params) {
return ajax("PUT", url, JSON.stringify(params));
}
// 放入本地缓存
this.setData = function (key, value) {
layui.data('LocalData', {
key: key,
value: value
})
};
// 获取本地缓存
this.getData = function (key) {
let localData = layui.data('LocalData');
return localData[key];
};
}
function ajax(type, url, data) {
return new Promise(function (resolve, reject) {
let roleSaveLoading = layer.msg('数据提交中,请稍候', {icon: 16, time: false, shade: 0.8});
$.ajax({
type: type,
url: config.baseURL + url,
contentType: "application/json; charset=utf-8",
data: data,
success: function (res) {
layer.close(roleSaveLoading);
// 进行业务处理
if (!res.success) {
layer.msg(res.message);
} else {
resolve(res);
}
},
error: function () {
layer.close(roleSaveLoading);
layer.msg("系统繁忙,请稍后再试!");
reject();
}
});
});
};
exports(MOD_NAME, flyio);
})
/**
* 全局路径引用容错处理
* */
window.rootPath = (function (src) {
src = document.scripts[document.scripts.length - 1].src;
return src.substring(0, src.lastIndexOf("/") + 1);
})();
/**
* 扩展包集成
* */
layui.config({
base: rootPath + "modules/",
version: true
}).extend({
flyio: "flyio"
});
<script>
layui.use(['form','flyio'], function () {
let form = layui.form;
let flyio = layui.flyio;
// 登 录 提 交
form.on('submit(login)', function (data) {
flyio.post('/auth/login', data.field).then(res => {
// 进行业务处理
console.log(data)
})
return false;
});
})
</script>