The front-end framework Layui realizes the dynamic table effect user management example (CRUD operation on the table - with source code)

Table of contents

I. Introduction

1. What is a form

2. Scope of use of the form

2. Case realization

1. Case Analysis

① Find the source code of the document according to the requirements

②The query result does not have this attribute in the entity

2.dao layer writing

①BaseDao tool class

②Written by UserDao

3. Servlet writing

①Introduction to R tools

②Useraction writing

4. jsp page construction

①userManage.jsp

 ②userEdit.jsp

③userManage.js

④userEdit.js

5. Case effect demonstration

① query

② Add

③ modify

④ delete


I. Introduction

Layui's dynamic tab & iframe use (with source code)

In the last use of the front-end framework Layui sharing tab, you can see that the path cannot be found by clicking on the left and right (because it has not been written), so this time based on the last content, add, delete, modify and check the user management page operate.

Because the url page here has not been written in my project, so 404 is inevitable, don't worry about it! ! !

1. What is a form

Table (Table) is a commonly used data display method in web development, which is used to present structured data in the form of rows and columns. Tables are composed of cells, and each cell can contain text, images, links, and more.

The table in HTML is defined by the <table> tag, <tr> represents the row of the table, and <td> represents the cell of the table. You can use the <th> tag to define the header of the table (header) .

Here is an example of a simple HTML table:

<table>
  <tr>
    <th>姓名</th>
    <th>年龄</th>
  </tr>
  <tr>
    <td>小明</td>
    <td>20</td>
  </tr>
  <tr>
    <td>小红</td>
    <td>22</td>
  </tr>
</table>

In this example, the table has two columns (name and age), the first row is the header, and the next two rows are the data rows. The content of each cell is contained in <td> tags, while the header cells use <th> tags.

By using tables, we can clearly organize and display a large amount of data, such as displaying employee lists, commodity price lists, course schedules, etc. You can use CSS to style the table, adjust the border style, background color, font style, etc. of the table to meet specific design requirements.

It should be noted that when using a table, an appropriate data structure and layout method should be selected according to specific needs. In some cases, using tables may not be the best solution, and you can consider using other data presentation methods, such as lists, card layouts, etc.

2. Scope of use of the form

Tables are widely used in different scenarios in web development. The following are some common usage areas of tables:

  • 1. Data display : Tables are a common form of data display, suitable for displaying structured data collections. For example, tables can be used to present user-facing data such as employee lists, product catalogs, order information, and so on.
  • 2. Data Analysis : Tables can be used to present, compare and analyze data in tabular form. Data can be better understood and interpreted by sorting, filtering, and calculating tables. Data analysis tools and reporting systems often use tables to present results.
  • 3. Ranking and comparison : Tables can be used to compare attributes or metrics of different items for ranking and sorting. For example, you can use a table to display the ranking of athletes, the test scores of students, and so on. Tables can sort data according to specific fields for easy search and comparison.
  • 4. Form input : Forms are often used in scenarios where users enter and edit data. For example, you can use forms to create registration forms, surveys, and more. Each table cell can contain various input fields (such as text boxes, check boxes, drop-down menus, etc.) to facilitate user input and submission of data.
  • 5. Schedules and timetables : Tables can be used to display schedules, class timetables, meeting schedules, etc. Each cell can represent a time period, and each row represents a point in time or an entity (such as a person, place, etc.).
  • 6. Responsive layout : The table can be adaptively laid out through CSS and responsive design techniques, so that it can maintain a good display effect under different screen sizes. Larger tables can be displayed on small screen devices by using features such as scrolling, hidden columns, adaptive width, and more.

It should be noted that the complexity and readability of the data should be considered when using tables. For large datasets or complex data structures, pagination, filtering, and searching capabilities can be used to improve the user experience. In addition, the reasonable use of styles and interactive effects can improve the usability and aesthetics of tables.

2. Case realization

1. Case Analysis

① Find the source code of the document according to the requirements

Layui 

This time the component we use is a table, so just find the desired component content on the official website and perform the "cv" operation.

②The query result does not have this attribute in the entity

We can observe that there is a field rid (role identity) in the table, but when the data is displayed, the numbers need to be converted into corresponding characters, so when we query the table, we need to add a field to display the role identity, but our eclipse There is no such attribute in the entity. If you encounter this kind of problem after writing another one, it will still be troublesome to write, so we can use the Map collection to save data.

More details will be explained slowly during the writing process. Please enjoy the code written by the editor below! ! !

2.dao layer writing

①BaseDao tool class

package com.zking.util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 所有Dao层的父类 BookDao UserDao OrderDao ...
 * 
 * @author Administrator
 *
 * @param <T>
 */
public class BaseDao<T> {

	/**
	 * 适合多表联查的数据返回
	 * @param sql
	 * @param pageBean
	 * @return
	 * @throws SQLException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	public List<Map<String, Object>> executeQuery(String sql, PageBean pageBean)
			throws SQLException, InstantiationException, IllegalAccessException {

		List<Map<String, Object>> list = new ArrayList<>();
		Connection con = DBAccess.getConnection();
		PreparedStatement pst = null;
		ResultSet rs = null;

		/*
		 * 是否需要分页? 无需分页(项目中的下拉框,查询条件教员下拉框,无须分页) 必须分页(项目中列表类需求、订单列表、商品列表、学生列表...)
		 */
		if (pageBean != null && pageBean.isPagination()) {
			// 必须分页(列表需求)
			String countSQL = getCountSQL(sql);
			pst = con.prepareStatement(countSQL);
			rs = pst.executeQuery();
			if (rs.next()) {
				pageBean.setTotal(String.valueOf(rs.getObject(1)));
			}

			// 挪动到下面,是因为最后才处理返回的结果集
			// -- sql=SELECT * FROM t_mvc_book WHERE bname like '%圣墟%'
			// -- pageSql=sql limit (page-1)*rows,rows 对应某一页的数据
			// -- countSql=select count(1) from (sql) t 符合条件的总记录数
			String pageSQL = getPageSQL(sql, pageBean);// 符合条件的某一页数据
			pst = con.prepareStatement(pageSQL);
			rs = pst.executeQuery();
		} else {
			// 不分页(select需求)
			pst = con.prepareStatement(sql);// 符合条件的所有数据
			rs = pst.executeQuery();
		}

		// 获取源数据
		ResultSetMetaData md = rs.getMetaData();
		int count = md.getColumnCount();
		Map<String, Object> map = null;
		while (rs.next()) {
			map = new HashMap<>();
			for (int i = 1; i <= count; i++) {
//				map.put(md.getColumnName(i), rs.getObject(i));
				map.put(md.getColumnLabel(i), rs.getObject(i));
			}
			list.add(map);
		}
		return list;

	}

	/**
	 * 
	 * @param sql
	 * @param attrs
	 *            map中的key
	 * @param paMap
	 *            jsp向后台传递的参数集合
	 * @return
	 * @throws SQLException
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public int executeUpdate(String sql, String[] attrs, Map<String, String[]> paMap) throws SQLException,
			NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
		Connection con = DBAccess.getConnection();
		PreparedStatement pst = con.prepareStatement(sql);
		for (int i = 0; i < attrs.length; i++) {
			pst.setObject(i + 1, JsonUtils.getParamVal(paMap, attrs[i]));
		}
		return pst.executeUpdate();
	}

	/**
	 * 批处理
	 * @param sqlLst
	 * @return
	 */
	public static int executeUpdateBatch(String[] sqlLst) {
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			conn = DBAccess.getConnection();
			// 设置不自动提交
			conn.setAutoCommit(false);
			for (String sql : sqlLst) {
				stmt = conn.prepareStatement(sql);
				stmt.executeUpdate();
			}
			conn.commit();
		} catch (Exception e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
				throw new RuntimeException(e1);
			}
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			DBAccess.close(conn, stmt, null);
		}
		return sqlLst.length;
	}

	/**
	 * 通用的增删改方法
	 * 
	 * @param book
	 * @throws Exception
	 */
	public int executeUpdate(String sql, T t, String[] attrs) throws Exception {
		// String[] attrs = new String[] {"bid", "bname", "price"};
		Connection con = DBAccess.getConnection();
		PreparedStatement pst = con.prepareStatement(sql);
		// pst.setObject(1, book.getBid());
		// pst.setObject(2, book.getBname());
		// pst.setObject(3, book.getPrice());
		/*
		 * 思路: 1.从传进来的t中读取属性值 2.往预定义对象中设置了值
		 * 
		 * t->book f->bid
		 */
		for (int i = 0; i < attrs.length; i++) {
			Field f = t.getClass().getDeclaredField(attrs[i]);
			f.setAccessible(true);
			pst.setObject(i + 1, f.get(t));
		}
		return pst.executeUpdate();
	}

	/**
	 * 通用分页查询
	 * 
	 * @param sql
	 * @param clz
	 * @return
	 * @throws Exception
	 */
	public List<T> executeQuery(String sql, Class<T> clz, PageBean pageBean) throws Exception {
		List<T> list = new ArrayList<T>();
		Connection con = DBAccess.getConnection();
		;
		PreparedStatement pst = null;
		ResultSet rs = null;

		/*
		 * 是否需要分页? 无需分页(项目中的下拉框,查询条件教员下拉框,无须分页) 必须分页(项目中列表类需求、订单列表、商品列表、学生列表...)
		 */
		if (pageBean != null && pageBean.isPagination()) {
			// 必须分页(列表需求)
			String countSQL = getCountSQL(sql);
			pst = con.prepareStatement(countSQL);
			rs = pst.executeQuery();
			if (rs.next()) {
				pageBean.setTotal(String.valueOf(rs.getObject(1)));
			}

			// 挪动到下面,是因为最后才处理返回的结果集
			// -- sql=SELECT * FROM t_mvc_book WHERE bname like '%圣墟%'
			// -- pageSql=sql limit (page-1)*rows,rows 对应某一页的数据
			// -- countSql=select count(1) from (sql) t 符合条件的总记录数
			String pageSQL = getPageSQL(sql, pageBean);// 符合条件的某一页数据
			pst = con.prepareStatement(pageSQL);
			rs = pst.executeQuery();
		} else {
			// 不分页(select需求)
			pst = con.prepareStatement(sql);// 符合条件的所有数据
			rs = pst.executeQuery();
		}

		while (rs.next()) {
			T t = clz.newInstance();
			Field[] fields = clz.getDeclaredFields();
			for (Field f : fields) {
				f.setAccessible(true);
				f.set(t, rs.getObject(f.getName()));
			}
			list.add(t);
		}
		return list;
	}

	/**
	 * 将原生SQL转换成符合条件的总记录数countSQL
	 * 
	 * @param sql
	 * @return
	 */
	private String getCountSQL(String sql) {
		// -- countSql=select count(1) from (sql) t 符合条件的总记录数
		return "select count(1) from (" + sql + ") t";
	}

	/**
	 * 将原生SQL转换成pageSQL
	 * 
	 * @param sql
	 * @param pageBean
	 * @return
	 */
	private String getPageSQL(String sql, PageBean pageBean) {
		// (this.page - 1) * this.rows
		// pageSql=sql limit (page-1)*rows,rows
		return sql + " limit " + pageBean.getStartIndex() + "," + pageBean.getRows();
	}
}

Tips:

Combined with the above case requirements, executeQuery is reconstructed here. It can be found that the return value here is no longer a collection entity but a Map collection stored in the list collection. In this way, even if there are more fields, we do not need to rewrite our entity class, just call In this method, use Map for storage.

②Written by UserDao

package com.xw.dao;

import java.util.List;
import java.util.Map;

import com.xw.entity.User;
import com.zking.util.BaseDao;
import com.zking.util.PageBean;
import com.zking.util.StringUtils;

/**
 * 用户
 * 
 * @author 索隆
 *
 */
public class UserDao extends BaseDao<User> {
	// 分页模糊查询
	public List<User> list(User user, PageBean pageBean) throws Exception {
		// sql语句编写
		String sql = "select * from t_oa_user where 1=1";
		// 获取参数
		long id = user.getId();
		String name = user.getName();
		// 进行参数非空判断
		if (StringUtils.isNotBlank(name)) {
			sql += " and name like '%" + name + "%'";
		}
		// 如果bid不等于0说明传递过来了bid,此时的bid是有值的
		if (id != 0) {
			sql += "and id=" + id;
		}
		return super.executeQuery(sql, User.class, pageBean);
	}

	// 新增
	public int add(User User) throws Exception {
		int n=0;
		// sql语句编写
		String sql = "insert into t_oa_user (name,loginName,pwd)values(?,?,?)";
		 n = super.executeUpdate(sql, User, new String[] { "name", "loginName", "pwd" });
		return n;
	}

	// 删除
	public int del(User User) throws Exception {
		// sql语句编写
		String sql = "delete from t_oa_user where id=?";
		return super.executeUpdate(sql, User, new String[] { "id" });
	}

	// 修改
	public int edit(User User) throws Exception {
		// sql语句编写
		String sql = "update t_oa_user set name=?,loginName=?,pwd=? where id=?";
		return super.executeUpdate(sql, User, new String[] { "name", "loginName", "pwd", "id" });
	}

	// 登录校验
	public User login(User User) throws Exception {
		// sql语句编写
		String sql = "select * from t_oa_user where loginName='" + User.getLoginName() + "' and pwd='" + User.getPwd()+ "' ";
		List<User> list = super.executeQuery(sql, User.class, null);
		if (list != null && list.size() == 1) {
			return list.get(0);
		} else {
			return null;
		}
	}

	
	//不包含原表字段的分页模糊查询
	public List<Map<String, Object>> userRole(User user, PageBean pageBean) throws Exception {
		// sql语句编写
		String sql = "select u.*,\r\n" + 
				"(CASE \r\n" + 
				"	WHEN u.rid='1' THEN	'管理员'\r\n" + 
				"	WHEN u.rid='2' THEN	'发起者'\r\n" + 
				"	WHEN u.rid='3' THEN	'审批者'\r\n" + 
				"	WHEN u.rid='4' THEN	'参与者'\r\n" + 
				"	WHEN u.rid='5' THEN	'会议室管理员'\r\n" + 
				"\r\n" + 
				"	ELSE\r\n" + 
				"		'其他'\r\n" + 
				"END ) rname\r\n" + 
				"from t_oa_user u WHERE 1=1";
		// 获取参数
		String name = user.getName();
		// 进行参数非空判断
		if (StringUtils.isNotBlank(name)) {
			sql += " and name like '%" + name + "%'";
		}
		return super.executeQuery(sql,pageBean);
	}

}

Note: The return here is the refactored executeQuery, don't confuse it! !

3. Servlet writing

①Introduction to R tools

We can check what the JSON format displayed in the table content on the official website looks like, and find that there are the following attributes:

code,msg,count,data

  • code: only "0" can be filled in (other people's Layui rules)
  • mag: has no actual meaning, you can fill it in at will
  • count: the number of records found
  • data: entity content

If we want to display data on the page, we must satisfy its JSON format. We can use the R tool class to simplify our code. Otherwise, we need to manually create a Map collection and add attributes with .put every time we encounter this scenario. way to create data.

package com.zking.util;

import java.util.HashMap;

public class R extends HashMap{
	public R data(String key, Object value) {
		this.put(key, value);
		return this;
	}
	
	public static R ok(int code, String msg) {
		R r = new R();
		r.data("success", true).data("code", code).data("msg", msg);
		return r;
	}
	
	public static R error(int code, String msg) {
		R r = new R();
		r.data("success", false).data("code", code).data("msg", msg);
		return r;
	}
	
	public static R ok(int code, String msg,Object data) {
		R r = new R();
		r.data("success", true).data("code", code).data("msg", msg).data("data", data);
		return r;
	}
	
	public static R ok(int code, String msg, long count, Object data) {
		R r = new R();
		r.data("success", true).data("code", code).data("msg", msg).data("count", count).data("data", data);
		return r;
	}
}

 Here we also refactored the ok method many times, so that we can use it in different scenarios.

②Useraction writing

package com.xw.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.xw.entity.User;
import com.xw.dao.UserDao;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
import com.zking.util.PageBean;
import com.zking.util.R;
import com.zking.util.ResponseUtil;

public class Useraction extends ActionSupport implements ModelDriver<User> {
	User user = new User();
	UserDao userdao = new UserDao();

	/**
	 * 登录验证
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	public void login(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		User login = userdao.login(user);
		// 保存域对象
		if (login != null) {
			HttpSession session = req.getSession();
			session.setAttribute("user", login);
		}
		ResponseUtil.writeJson(resp, login);

	}


	/**
	 * 注册新增用户
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	public void register(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		int i = userdao.add(user);
		if (i > 0) {
			ResponseUtil.writeJson(resp, i);
		} else {
			ResponseUtil.writeJson(resp, null);
		}
	}
	
	
	
	/**带分类管理的模糊查询
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	public void UserRole(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		// 初始化pageBean
		PageBean pageBean = new PageBean();
		pageBean.setRequest(req);
		//调用带分页查询的方法
		List<Map<String, Object>> userRole = userdao.userRole(user, pageBean);
		//利用R工具类制造出符合要求的json格式数据
		 ResponseUtil.writeJson(resp, R.ok(0, "查询成功", pageBean.getTotal(), userRole));

	}
	
	
	/**删除用户
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	public void del(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		//调用删除的方法
		int del = userdao.del(user);
		//利用R工具类制造出符合要求的json格式数据
		 ResponseUtil.writeJson(resp, R.ok(0, "删除成功"));

	}
	
	
	/**修改用户
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	public void edit(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		//调用修改的方法
		int del = userdao.edit(user);
		//利用R工具类制造出符合要求的json格式数据
		 ResponseUtil.writeJson(resp, R.ok(0, "修改成功"));

	}
	
	
	/**新增用户
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	public void add(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		//调用新增的方法
		int del = userdao.add(user);
		//利用R工具类制造出符合要求的json格式数据
		 ResponseUtil.writeJson(resp, R.ok(0, "新增成功"));

	}
	
	
	

	@Override
	public User getModel() {
		return user;
	}

}

4. jsp page construction

Be sure to pay attention to our hierarchy

①userManage.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	<%@ include file="/common/static.jsp"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户管理</title>
<script type="text/javascript" src="static/js/system/userManage.js"></script>
</head>

<body>
<!-- 搜索栏 -->
	<div class="layui-form-item">
	  <div class="layui-inline">
	    <label class="layui-form-label">用户名:</label>
	    <div class="layui-input-inline">
	      <input type="text" id="name" placeholder="请输入用户名" autocomplete="off" class="layui-input">
	    </div>
	  </div>
	  
	  <div class="layui-inline">
	    <div class="layui-input-inline">
	      <button id="btn_search" type="button" class="layui-btn layui-btn-normal">
	      	<i class="layui-icon layui-icon-search"></i>
	      	查询
	      </button>
	      <button id="btn_add" type="button" class="layui-btn">新增</button>
	    </div>
	  </div>
	  
	</div>
 
<table class="layui-hide" id="test" lay-filter="test"></table>
 

 
<script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
              
          
 
<script>

</script>

</body>
</html>

 ②userEdit.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="/common/static.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="static/js/system/userEdit.js"></script>
<title>用户新增</title>
</head>
<style>
.layui-form-select dl{
	max-height:150px;
}
</style>
<body>
<div style="padding:10px;">
    <form class="layui-form layui-form-pane" lay-filter="user">
        <input type="hidden" name="id"/>
        <div class="layui-form-item">
            <label class="layui-form-label">用户名称</label>
            <div class="layui-input-block">
                <input type="text" id="name" name="name" autocomplete="off" placeholder="请输入用户名" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户角色</label>
            <div class="layui-input-block">
                <select name="rid">
                    <option value="">---请选择---</option>
                    <option value="1">管理员</option>
                    <option value="2">发起者</option>
                    <option value="3">审批者</option>
                    <option value="4">参与者</option>
                    <option value="5">会议管理员</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">登录账号</label>
            <div class="layui-input-block">
                <input type="text" name="loginName" lay-verify="required" placeholder="请输入账号" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">登录密码</label>
            <div class="layui-input-block">
                <input type="password" name="pwd" placeholder="请输入密码" autocomplete="off" class="layui-input">
            </div>
        </div>
    </form>
</div>
</body>
</html>

Separate the logic code of the JSP page

③userManage.js

var table,$,layer;
var row;

layui.use(['table','jquery','layer'], function(){
  table = layui.table
  ,layer=layui.layer
  ,$=layui.jquery;
  
  initTable();
  
  //为查询按钮设置点击事件
  $("#btn_search").click(function(){
	  query();
  })
  
  //为新增按钮设置点击事件
  $("#btn_add").click(function(){
	  row=null;
	  edit('新增');
  })
  
});

//新增/修改的点击事件
function edit(title){
	  layer.open({
	       type: 2,                    //layer提供了5种层类型。可传入的值有:0(信息框,默认)1(页面层)2(iframe层)3(加载层)4(tips层)
	       title:title,
	       area: ['660px', '340px'],   //宽高
	       skin: 'layui-layer-rim',    //样式类名
	       content:  'jsp/system/userEdit.jsp', //书本编辑页面
	       btn:['保存','关闭'],
	       yes: function(index, layero){
	    	   //调用子页面中提供的getData方法,快速获取子页面的form表单数据
	           let data= $(layero).find("iframe")[0].contentWindow.getData();
	           console.log(data);
	           //判断title标题
	           let methodName="add";
	           if(title=="编辑")
	        	   methodName="edit";
	           $.post('user.action?methodName='+methodName,
	        		   data,function(rs){
	        	   if(rs.success){
	        		   //关闭对话框
	        		   layer.closeAll();
	        		   //调用查询方法刷新数据
	        		   query();
	        	   }else{
	        		   layer.msg(rs.msg,function(){});
	        	   }
	           },'json');
	       },
	       btn2: function(index, layero){
	    	   layer.closeAll();
	       }
	    });
}



//查询的点击事件
function query(){
	//表格的重载
	table.reload('test', {
		  where: { //设定异步数据接口的额外参数,任意设
		    name: $("#name").val()
		  }
	//默认limit需要改成我们自己工具类的名字
		,request: {
	    pageName: 'page ' //页码的参数名称,默认:page
	    ,limitName: 'rows' //每页数据量的参数名,默认:limit
	  }
		}); //只重载数据
}




//将分页查询方法封装
function initTable(){
	 table.render({
		    elem: '#test'
		    ,url:'user.action?methodName=UserRole'
		    ,toolbar: '#toolbarDemo' //开启头部工具栏,并为其绑定左侧模板
		    ,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可
		      title: '提示'
		      ,layEvent: 'LAYTABLE_TIPS'
		      ,icon: 'layui-icon-tips'
		    }]
		    ,title: '用户数据表'
		    ,cols: [[
		      {type: 'checkbox', fixed: 'left'}
		      ,{field:'id', title:'ID', width:80, fixed: 'left', unresize: true, sort: true}
		      ,{field:'loginName', title:'账户名', width:120, edit: 'text'}
		      ,{field:'name', title:'真实姓名', width:150, edit: 'text', templet: function(res){
		        return '<em>'+ res.name +'</em>'
		      }}
		      ,{field:'pwd', title:'密码', width:80, edit: 'text', sort: true}
		      ,{field:'rname', title:'身份', width:100}
		      ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:150}
		    ]]
		    ,page: true
		  });
		  
		  
		  
		  //监听行工具事件
		  table.on('tool(test)', function(obj){
		     row = obj.data;
		    if(obj.event === 'del'){
		    	  layer.confirm('确认删除吗?', {icon: 3, title:'提示'}, function(index){
					  $.post('user.action',{
						  'methodName':'del',
						  'id':row.id
					  },function(rs){
						  if(rs.success){
			        		   //调用查询方法刷新数据
			        		   query();
			        	   }else{
			        		   layer.msg(rs.msg,function(){});
			        	   }
					  },'json');
					  layer.close(index);
					});
		    } else if(obj.event === 'edit'){
		    	 edit('编辑');
		    }
		  });
}

④userEdit.js

let layer,form,$;
layui.use(['layer','form','jquery'],function(){
	layer=layui.layer,form=layui.form,$=layui.jquery;
	initData();
});

function initData(){
	console.log(parent.row);
	if(null!=parent.row){
	     //因为layui.each内部的逻辑问题导致的所以要先深拷贝一份然后再去val
	     //parent.row:表格行对象
	     form.val('user',$.extend({}, parent.row||{}));
	     $('#name').attr('readonly','readonly');
	}
}

function getData(){
    return form.val('user');
}

5. Case effect demonstration

① query

 

② Add

 

③ modify

 

④ delete

 

My sharing is over here, welcome to the comment area to discuss and communicate! !

If you find it useful, please give it a thumbs up ♥ ♥

Guess you like

Origin blog.csdn.net/weixin_74318097/article/details/131732594