由于项目写了一大半需要添加的全局性的东西太多,故封装了这种修改比较小的方式。
commonRequest.js
layui.define(['jquery','table'], function(exports){
var $ = layui.jquery,table=layui.table;
var obj = {
ajax: function (obj) {
if (!obj.headers) {
obj.headers = {
// 兼容IE9
'cache-control': 'no-cache',
'Pragma': 'no-cache',
'Authorization': window.sessionStorage.getItem("token")
};
}
if (!obj.type) obj.type = "GET";
if (!obj.dataType) obj.dataType = "json";
// 配置为false时,表示不从浏览器缓存中获取数据,调试时可以看到,发Get请求时,会自动加上时间戳
if (!obj.cache) obj.cache = false;
if (!obj.async) obj.async = true;
obj.crossDomain = true === !(document.all);//这句是关键
if (!obj.error) {
obj.error = function (err) {
layer.msg("网络连接失败!");
console.log(err);
}
}
console.log(obj);
$.ajax(obj);
},
render: function (obj) {
obj.headers = {
'cache-control': 'no-cache',
'Pragma': 'no-cache',
'Authorization': window.sessionStorage.getItem("token")
};
console.log(obj);
table.render(obj);
}
};
//输出接口
exports('commonRequest', obj); // 使用的模块名称
});
配置configRequest.js
注意:一个html中layui.config只能有一个
layui.config({base: '../../../../common/' //自定义layui组件的目录
}).extend({ //设定组件别名
common: 'commonRequest',
});
引入
// 如果有别的模块配置在下面使用页面,这种方法会报错
使用
layui.use(['table','commonRequest'],function(){
var table=layui.table, commonRequest=layui.commonRequest;
// 表格渲染
commonRequest.render({
elem: tableConfig.elem, //指定原始表格元素选择器(推荐id选择器)
height: tableConfig.height, //容器高度
cols: tableConfig.cols, //设置表头
url: tableConfig.params ? tableConfig.getUrl() : url,
page: tableConfig.page != false ? true : false,
where: requestParam,
headers: {'Authorization': window.sessionStorage.getItem("token")}
})
// ajax请求
commonRequest.ajax({
type: "POST",
url: url,
data: data,
dataType: "json",
success: function(data) {
}
});
})