要实现的功能如下:根据执行状态判断是否可以导出。如果可以导出,点击导出,在浏览器里下载对应的文件。
代码实现 |
html里:
<table class="layui-hide" id="studentTable" lay-filter="studentTable"></table>
js里:
studentTable.loadTable = function() {var form = layui.form;table = layui.table;table.render({elem: '#studentTable',url: ctx + '/studentTable/getList.shtml',method: "post",toolbar: "#toolbarWarp",defaultToolbar: [],parseData: function(jsonData) {if (jsonData.code == '200') {var data = jsonData.data;return {"code": jsonData.code,"msg": jsonData.message,"total": data.total,"rows": data.list}}return {data: []};},text: {none: '暂无相关数据'},request: { //分页pageName: 'pageNo',limitName: 'pageSize'},response: {statusName: 'code',statusCode: "200",msgName: 'msg',countName: 'total',dataName: 'rows'},page: true,limits: [10, 20, 30, 40, 50, 60, 70, 80, 90],cellMinWidth: 100,cols: [[{type: 'radio',fixed: 'left'},{field: 'status',title: '执行状态',sort: false,align: 'center',templet: function(row) {if (row.status == '1') {return "待执行";}if (row.status == '2') {return "执行完毕";}if (row.status == '3') {return "暂停";}return "未知";}},{field: 'opeate',title: '操作',sort: false,align: 'center',fixed: "right",templet: function(row) {var result;if (row.status == '2') {result = '<a class="layui-btn layui-btn-xs" href="javascript:studentTable.export(\'' + row.code + '\')">导出</a>';} else {result = '<a class="layui-btn layui-btn-disabled layui-btn-xs">导出</a>';}return result;}}]]});studentTable.export = function(code) {$.ajax({type: "post",data: {code: code},url: ctx + "/studentTable/export.shtml",success: function(data) {// msg("导出成功");var localObj = window.location; //当前页面地址var protocol = location.protocol; //http/httpsvar host = localObj.host; //地址栏IP和端口号var contextPath = localObj.pathname.split("/")[1]; //项目名if (!data.includes("false")) {window.location.href = protocol + "//" + host + "/" + contextPath + data;} else {errorAlert("导出失败");}},error: function(XMLHttpRequest, textStatus, errorThrown) {errorAlert("系统异常");}});}
代码块解读:
1、定义了导出按钮,而且去调用了同文件中的export()方法:
result = '<a class="layui-btn layui-btn-xs" href="javascript:studentTable.export(\'' + row.code + '\')">导出</a>';
2、 让浏览器跳转到新的url,即开始下载excel文件:
window.location.href = protocol + "//" + host + "/" + contextPath + data;
3、实现思路大概为:
(1)调用后端查询列表方法,在<操作>列,定义导出按钮,并去调用export()方法
(2)在export()里,去调用后端导出方法。
(3)后端导出方法要做的工作有:根据传入的code查询出数据,填充到excel里;将excel上传到服务器上;最后将文件地址返回给前端。
(4)export()方法接收到这个url地址后,请求这个地址,在h5页面下载excel文件
小结 |
这个导出按钮是在js里添加并实现逻辑的,和之前是在html里添加的不一样。