Layui动态添加表头

需求:根据选择查询条件,动态添加clo列,并展示结果
实现效果如下:

Layui动态添加表头_第1张图片

1.使用到的技术与组件:
layui、xm-select.js、axios.min.js、jquery,axios上干货:

```java
package com.yhh.search.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.yhh.common.entity.LayuiTable;
import com.yhh.common.entity.PageParam;
import com.yhh.search.entity.dto.CusOverheadAccountRecordDTO;
import com.yhh.search.service.CusOverheadAccountRecordService;

@Controller
@RequestMapping(value = "/manage/CusOverheadAccountRecordController")
public class CusOverheadAccountRecordController {
	
	//这是java中的组合,通过CusOverheadAccountRecordService生成cusOverheadAccountRecordService对象进行组合
	@Autowired
	private CusOverheadAccountRecordService cusOverheadAccountRecordService;
	
	@RequestMapping(value = "/getCusOverheadAccountRecord")
	@ResponseBody
    public LayuiTable getCusOverheadAccountRecord(
			HttpSession session, CusOverheadAccountRecordDTO cusOverheadAccountRecordDTO, Integer page,
			Integer rows, String sortName, String sortOrder) {

		LayuiTable table = new LayuiTable();
		try {
			List listRows = new ArrayList();
			PageParam params = new PageParam(
					cusOverheadAccountRecordDTO, page, rows, sortName, sortOrder);
			String selectArr = cusOverheadAccountRecordDTO.getSelectArr();
			JSONArray parseArray = JSONArray.parseArray(selectArr);
			if(parseArray.size() == 0){
				table.setMsg("请输入选择产品再进行查询哦");
				table.setData(listRows);
				table.setCount(0);
				return table;
			}
			cusOverheadAccountRecordDTO.setListCo(parseArray);
			// 获取数据集合
			listRows = cusOverheadAccountRecordService.getCusOverheadAccountRecordPage(params);
			// 获取总条数
			Integer total = cusOverheadAccountRecordService.getCusOverheadAccountRecordCount(cusOverheadAccountRecordDTO);
			// 存储到LayuiTable 对象
			table.setData(listRows);
			table.setCount(total);
			return table;
		} catch (Exception e) {
			e.printStackTrace();
			return table;
		}
	}

}



<mapper namespace="com.yhh.search.dao.CusOverheadAccountRecordDAO">

	<select id="getCusOverheadAccountRecordPage" resultType="java.util.Map">
		  SELECT  C.CUSTOMERNUMBER,
					C.CUSTOMERNAME,
					C.ORGNAME,
					CC.MOBILEPHONENO
			<if test='queryParams.listCo != null'>
			,
	        <foreach collection="queryParams.listCo" item="item" separator=",">
	        MAX(CASE C.paymentbanknumber WHEN #{item} THEN '开通' END ) "${item}"
	        foreach>
	    if>
		  FROM CUS_OVERHEAD_ACCOUNT_RECORD C
			INNER JOIN CUS_CUSTOMER CC
				ON C.CUSTOMERNUMBER = CC.PKCUS
			INNER JOIN BAS_ORGANIZATION BO
                ON BO.PKORG = C.PKORG
              START WITH BO.PKORG = #{queryParams.pkorg}
		CONNECT BY PRIOR BO.PKORG = BO.PKPARENT
		  GROUP BY C.CUSTOMERNUMBER,C.CUSTOMERNAME,C.ORGNAME,
					CC.MOBILEPHONENO
		OFFSET #{startNumber} ROWS FETCH NEXT #{rows} ROWS ONLY
	select>
	
	<select id="getCusOverheadAccountRecordCount" resultType="java.lang.Integer">
		SELECT COUNT(*)  FROM CUS_OVERHEAD_ACCOUNT_RECORD C
			     INNER JOIN CUS_CUSTOMER CC
						ON C.CUSTOMERNUMBER = CC.PKCUS
			     INNER JOIN BAS_ORGANIZATION BO
                        ON BO.PKORG = C.PKORG
                 START WITH BO.PKORG = #{pkorg}
					CONNECT BY PRIOR BO.PKORG = BO.PKPARENT
					
	select>

mapper>
```html
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>


<html>
<head>
<base href="<%=basePath%>">

<title>客户业务查询title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<link rel="stylesheet"
	href="<%=basePath%>jslib/plugins/layui/css/layui.css" media="all" />

<script type='text/javascript' src="<%=basePath%>jslib/jquery.min.js">script>
<script type='text/javascript' src="<%=basePath%>jslib/jaliswall.js">script>
<script type="text/javascript" src="<%=basePath%>jslib/urlparenter.js">script>
<script type="text/javascript" src="<%=basePath%>jslib/layer/layer.js">script>
<script type="text/javascript" src="<%=basePath%>jslib/lverification.js">script>
<script src="<%=basePath%>jslib/plugins/layui/layui.js">script>
<script src="<%=basePath%>jslib/plugins/layui/xm-select.js">script>
<script src="<%=basePath%>jslib/plugins/layui/axios.min.js">script>
<style>
body {
	margin: 0;
	padding: 0;
	overflow: hidden;
}

.layui-table-view {
	margin: 0;
}
.layui-form-item {
	margin-bottom: 0px;
}
.layui-form-item .layui-inline:last-child {
	margin-right: 0;
	margin-left: 0px;
}
.layui-col-md11{
	margin:0 auto;
}
.layui-form-item{margin-top:14px;}

.layui-form-pane .layui-form-label{
	display: flex;
	align-items: center;
	justify-content: center;
}

style>
head>

<body>
	<form class="layui-form" action="" id="form" method="post"
		style="padding: 10px 0px;">
		<div class="layui-form-item" style="margin-top: 0px;">
				<div class="layui-inline" style="width:1200px;">
					<label class="layui-form-label">机构名称:label>
					<div class="layui-input-inline" style="width:120px;">
							<select id="org_modules" name="modules"  lay-verify="required" lay-filter="org_modules"  >select>
					div>
					<label class="layui-form-label">开通产品:label>
					<div class="layui-input-inline" style="width:360px;">
						<div id="demo1">div>
					div>
					<a class="layui-btn search_btn search_btn_reload" id="demo1-getValue"  data-type="reload">查询a>
				div>
		div>
		<div class="layui-form-item" style="margin-top: 0px;">
		div>
	form>

	
	
	<table class="layui-hide" id="test" lay-filter="test">table>
	
	<script type="text/javascript">
			var demo1 = xmSelect.render({
				el: '#demo1', 
				toolbar: {show: true},
				model: {
				label: {
						type: 'block',
						block: {
							//最大显示数量, 0:不限制
							showCount: 3,
							//是否显示删除图标
							showIcon: true,
						}
					}
				},
				data: []
			})
			/*axios获取产品*/
			axios({
				method: 'get',
				url: "${pageContext.request.contextPath}/manage/BizBankProductController/getBizBankProduct",
			}).then(response => {
				var res = response.data;
				demo1.update({
					data: res,
					autoRow: true,
				})
			});
	script>
	<script>
var pksta = '<%=session.getAttribute("pksta")%>';
var pkorg = <%=session.getAttribute("pkorg")%>;
layui.use([ 'laydate', 'laypage', 'layer', 'table', 'form','laytpl' ],
	function() {
		var laydate = layui.laydate, laypage = layui.laypage, $ = layui.jquery, laytpl = layui.laytpl, form = layui.form, layer = layui.layer, table = layui.table;
		var form_height = document.getElementById("form").offsetHeight;
		var table_height = "full-" + form_height;
		var form_width = document.getElementById("form").offsetWidth;
		util = layui.util,
		rederSelect("bas_org","#org_modules","");
		form.on('select(org_modules)',function(obj){
			pkorg = obj.value;
		});
		rederSelectPko("aaa","#pkog","产品");
		form.on('select(pkog)',function(obj){
			pkog = obj.value;
		});
		/* 渲染 select */
      function rederSelect(tablename,div_id,selectValue){
	      $.ajax({
			url:"${pageContext.request.contextPath}/common/dicData/getTypeAlls2",
			type:"POST",
		    dataType:"json",
		    data:{
		       'filedname':'<%=session.getAttribute("pkorg")%>'
		    },
		    async: true,
	  		success:function(requestData){
	  			var o_html ="";
	 	        for(var i = 0; i < requestData.obj.length+1; i++) {
	    	        if (i == 0){
	          	        //o_html += '';
	          		}else{
	             	    var sys = requestData.obj[i-1];
	              	     o_html += ' + sys.text + '';
	              	}
	           	}
	            $(div_id).append(o_html);
		        form.render('select');
	  		          },error:function(){
	  		        }
	        })
	    }   //pko 网格获取
	    function rederSelectPko(tablename,div_id,selectValue){
	      $.ajax({
			url:"${pageContext.request.contextPath}/manage/CusSearchController/getProduct",
			type:"POST",
		    dataType:"json",
		    data:{},
		    async: true,
	  		success:function(table){
	  			var o_html ="";
	 	        for(var i = 0; i < table.data.length+1; i++) {
	    	        if (i == 0){
	          	        o_html += '';
	          		}else{
	             	    var sys = table.data[i-1];
	              	    o_html += ' + sys.bpname + '';
	              	}
	           	}
	            $(div_id).append(o_html);
		        form.render('select');
	  		          },error:function(){
	  		        }
	        })
	    }
	    
	    //定义一个固定表头
	    var col = [ //表头
				{
					title : '序号',
					type : 'numbers',
					fixed : 'left',
					width : 80,
					align : 'center',
				},
	            {
	                field: 'CUSTOMERNAME',
	                title: '客户名称',
	                minWidth: 120,
	                align: 'center'
	            },{
	                field: 'ORGNAME',
	                title: '所属机构',
	                align: 'center',
	                minWidth: 170,
	            },
	            {
	                field: 'MOBILEPHONENO',
	                title: '手机号码',
	                align: 'center',
	                minWidth: 120
	            }
				]
		table.render({elem : '#test',
			url: "${pageContext.request.contextPath}/manage/CusOverheadAccountRecordController/getCusOverheadAccountRecord",
			type : 'POST',
			dataType : 'JSON',
			request : {
				pageName : 'page',
				limitName : 'rows'
			},
			where : {
				pkorg : pkorg,
				selectArr:"[]"
			},
			cellMinWidth : 95,
			height : table_height,
			width : form_width,
			page : true,
			id : 'newsListTable',
			limit : 20,
			limits : [ 10, 20, 30, 40, 50 ],
			cols :[col]
			});
			var indexload;
			$(".search_btn_reload").on("click",function(){
			indexload = layer.load(2, {time: 10*10000});
     	});
     	
     	//组件获取多选值
		document.getElementById('demo1-getValue').onclick = function(){
		    //获取当前多选选中的值
		    var selectArr = demo1.getValue();
		    reloadesData(selectArr);
		}
		
     	window.reloadesData = function(selectArr){
     			var colss = [ //表头
				{
					title : '序号',
					type : 'numbers',
					fixed : 'left',
					width : 80,
					align : 'center',
				},
	            {
	                field: 'CUSTOMERNAME',
	                title: '客户名称',
	                minWidth: 120,
	                align: 'center'
	            },{
	                field: 'ORGNAME',
	                title: '所属机构',
	                align: 'center',
	                minWidth: 170,
	            },
	            {
	                field: 'MOBILEPHONENO',
	                title: '手机号码',
	                align: 'center',
	                minWidth: 120
	            }
				]
     		//对所选的数组进行遍历,然后进行push拼接动态表头
		    for(var i =0;i<selectArr.length;i++) {
			   	colss.push({field: selectArr[i].value, title: selectArr[i].name, width: '120', align:'center'});
		    }

			/**
			1:arr是一个对象集合。或者是你要需要的目标的集合
			2:push()方法是数组的栈底添加 意思是往数组的底部添加
			3:unshift()方法是数组的栈顶添加 意思是往数组的头部添加
			**/
			var arr = [];
			for(var i =0;i<selectArr.length;i++){
				arr.push(selectArr[i].value);
				//arr.unshift(selectArr[i].value);
			};
			table.render({elem : '#test',
			url: "${pageContext.request.contextPath}/manage/CusOverheadAccountRecordController/getCusOverheadAccountRecord",
			type : 'POST',
			dataType : 'JSON',
			request : {
				pageName : 'page',
				limitName : 'rows'
			},
			where : {
				pkorg:pkorg,
	            selectArr:JSON.stringify(arr)
			},
			cellMinWidth : 95,
			height : table_height,
			width : form_width,
			page : true,
			id : 'newsListTable',
			limit : 20,
			limits : [ 10, 20, 30, 40, 50 ],
			cols :[colss],
			parseData: function(res){ //res 即为原始返回的数据
	            	if(res.msg != ""){
	            		layer.msg(res.msg, {
						  icon: 6,
						  time: 1000 //2秒关闭(如果不配置,默认是3秒)
						}, function(){
	            		  //window.location.reload();
						})
	            	};
	            	layer.close(indexload);
			    }
			});
     	}
 })
	script>

body>
html>

你可能感兴趣的:(Java)