目录
一、数据表格table 通过id来获取,动态获取
二、通过js动态获取数据表格数据,包括数据单元格的查看、编辑、删除
三、通过ajax实现局部刷新刷新(ajax异步请求)重点解决无法获取输入框的问题
四、Servlet+分页查询
五、封装json数据,不然 layui框架那边无法获取数据
六、底层数据逻辑以及实体类
二、通过js动态获取数据表格数据,包括数据单元格的查看、编辑、删除
动态获取表格
layui.use('table', function(){
var table = layui.table;
var dropdown = layui.dropdown;
//第一个实例sousuo
table.render({
elem: '#demo'
// ,toolbar: '#toolbarDemo'
,height: 'full-160'
// ,height: 'full-200' // 最大高度减去其他容器已占有的高度差
,cellMinWidth: 100
,url: '/ceshi?action=query' //数据接口//直接调用不需要跳转
,page: true //开启分页
// ,totalRow: true // 开启合计行得在前端传输数据:count//下面会多出空格//totalRowText: "合计"
,cols: [[ //表头
{type: 'checkbox', fixed: 'left',width: 80,align: 'center',totalRowText: "合计"}
,{field: 'eId', title: '编号', width:80, sort: true, fixed: 'left'}
,{field: 'eAccount', title: '账户', width:80}
,{field: 'ePassword', title: '密码', width:80, sort: true}
,{field: 'eName', title: '姓名', width:80, sort: true}
,{field: 'eSex', title: '性别', width:80, sort: true}
,{field: 'eEducation', title: '学历', width:80, sort: true}
,{field: 'dName', title: '部门', width:120, sort: true}
,{field: 'ePosition', title: '职称', width:80, sort: true}
,{field: 'eIdcard', title: '身份证号码', width:180, sort: true}
,{field: 'ePhone', title: '手机号码', width:120, sort: true}
,{field: 'eAddress', title: '家庭地址', width:120, sort: true}
,{field: 'eEntrytime', title: '入职时间', width:120, sort: true}
,{fixed: 'right', title:'操作', width: 200, minWidth: 125, toolbar: '#barDemo'}
]]
// , page:true
,limit:10
,limits:[5,10,20,30,40,50]
, parseData: function (res) { //res 即为原始返回的数据
console.log("成功"+res.status+";=="+res.message+";"+res.total);
return {
"code": res.status, //解析接口状态
"msg": res.message, //解析提示文本
"count": res.total, //解析数据长度
"data": res.data //解析数据列表
};
}
,done: function(){
var id = this.id;
}
,error: function(res, msg){
console.log(res, msg)
}
});
// 工具栏事件
table.on('toolbar(test)', function(obj){
var id = obj.config.id;
var checkStatus = table.checkStatus(id);
var othis = lay(this);
switch(obj.event){
case 'getCheckData':
var data = checkStatus.data;
layer.alert(layui.util.escape(JSON.stringify(data)));
break;
case 'getData':
var getData = table.getData(id);
console.log(getData);
layer.alert(layui.util.escape(JSON.stringify(getData)));
break;
case 'isAll':
layer.msg(checkStatus.isAll ? '全选': '未全选')
break;
case 'multi-row':
table.reload('test', {
// 设置行样式,此处以设置多行高度为例。若为单行,则没必要设置改参数 - 注:v2.7.0 新增
lineStyle: 'height: 95px;'
});
layer.msg('即通过设置 lineStyle 参数可开启多行');
break;
case 'default-row':
table.reload('test', {
lineStyle: null // 恢复单行
});
layer.msg('已设为单行');
break;
case 'LAYTABLE_TIPS':
layer.alert('Table for layui-v'+ layui.v);
break;
};
});
//触发单元格工具事件
table.on('tool(test)', function(obj){ // 双击 toolDouble
var data = obj.data;//获取当前的行的数据
//obj.data :获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
console.log(obj.data)
//console.log(obj)
if(obj.event === 'detail'){ //查看
layer.alert('编号:'+ data.eId +"
"+'账户:'+data.eAccount+"
"+'密码:'+data.ePassword+"
"+
'姓名:' +data.eName+"
"+'性别:' +data.eSex +"
"+'学历:'+data.eEducation +"
"+'部门:'
+data.dName +"
"+'职称:'+data.ePosition +"
"+'身份证号码:'+data.eIdcard +"
"+'手机号码:'
+data.ePhone +"
"+'家庭地址:'+data.eAddress +"
"+'入职时间:'+data.eEntrytime);
}else if(obj.event === 'del'){
layer.confirm('真的删除员工吗?', function(index){
console.log(index)
console.log(data.eId)
obj.del();
// location.href="updatebyid?flag=all&eId="+eid;
// location.href="updatebyid?flag=all&eId="+eid+"&xxx"+xxx;
// location.href="updatetongyi?eId="+userId;
location.href = "/newsWork?action=delwork&eId="+data.eId;
layer.close(index);
});
} else if(obj.event === 'edit'){
layer.open({
title: '编辑',
type: 1,
area: ['80%','80%'],
content: ' '
});
}
});
//触发表格复选框选择
table.on('checkbox(test)', function(obj){
console.log(obj)
});
//触发表格单选框选择
table.on('radio(test)', function(obj){
console.log(obj)
});
// 行单击事件
table.on('row(test)', function(obj){
//console.log(obj);
//layer.closeAll('tips');
});
// 行双击事件
table.on('rowDouble(test)', function(obj){
console.log(obj);
});
// 单元格编辑事件
table.on('edit(test)', function(obj){
var field = obj.field //得到字段
,value = obj.value //得到修改后的值
,data = obj.data; //得到所在行所有键值
var update = {};
update[field] = value;
obj.update(update);
});
});
三、通过ajax实现局部刷新刷新(ajax异步请求)重点解决无法获取输入框的问题
<%----%>
layui.use(['form', 'jquery', 'layer'], function () {
var form = layui.form;
var $ = layui.$;
var layer = layui.layer;
let serch = $("#serch").val();
//通过点击事件获取。不然获取不了input里面的值
$(function () {
$("#123").click(function () {
// alert($("textarea[name='comment']").val());
// console.log($("textarea[name='comment']").val())
alert($("input[name='eName']").val());
console.log($("input[name='eName']").val())
let action = $("input[name='eName']").val()
console.log(action)
$.ajax( {
url : "/ceshi?action=mohu&eName="+action, // 要提交的URL路径
type : "post", // 发送请求的方式
// 要发送到服务器的数据
dataType: "JSON", // 指定传输的数据格式
beforeSend: function() { //请求之前的方法
},
success : function(result) {
let d = result;
console.log(result)
console.log(d)
console.log(d.data.eId)
console.log(result.data.eId)
layui.use(['form','jquery','table','layer'],function(){
var form = layui.form;
var $ = layui.jquery;
var table = layui.table;
var layer = layui.layer;
table.render({
elem:"#demo",
data:d
,height: 'full-160'
// ,height: 'full-200' // 最大高度减去其他容器已占有的高度差
,cellMinWidth: 100
,page: true, //开启分页c
url : "/ceshi?action=mohu&eName="+action,//调用接
cols: [[ //表头
{
type: 'checkbox', fixed: 'left',width: 80,align: 'center',totalRowText: "合计"}
,{field: "eId", title: '编号', width:80, sort: true, fixed: 'left'}
,{field: 'eAccount', title: '账户', width:80}
,{field: 'ePassword', title: '密码', width:80, sort: true}
,{field: 'eName', title: '姓名', width:80, sort: true}
,{field: 'eSex', title: '性别', width:80, sort: true}
,{field: 'eEducation', title: '学历', width:80, sort: true}
,{field: 'dName', title: '部门', width:120, sort: true}
,{field: 'ePosition', title: '职称', width:80, sort: true}
,{field: 'eIdcard', title: '身份证号码', width:180, sort: true}
,{field: 'ePhone', title: '手机号码', width:120, sort: true}
,{field: 'eAddress', title: '家庭地址', width:120, sort: true}
,{field: 'eEntrytime', title: '入职时间', width:120, sort: true}
,{fixed: 'right', title:'操作', width: 200, minWidth: 125, toolbar: '#barDemo'}
]],
parseData: function(d) { //res 即为原始返回的数据
return {
"code": 0, //解析接口状态
"msg": "ok", //解析提示文本
"count": 100, //解析数据长度
"data": d //解析数据列表
}
}
});
});
// 请求成功后要执行的代码
console.log("成功")
},
error : function() { // 请求失败后要执行的代码
console.log("失败")
}
} );
})
})
// let aaa =$("textarea[name='comment']").val()
// console.log($("textarea[name='comment']").val())
// console.log("=="+aaa)
// console.log(serch)
// console.log(form)
// console.log(form)
// console.log(form)
// console.log($("[name='eName']").val())
// var a= document.getElementById("chaxun").innerText
// var a= document.getElementById("chaxun").innerHTML
// alert(a);
// console.log("xx")
// console.log(a)
// console.log("xx")
// console.log("xx")
});
四、Servlet+分页查询
package com.lingnan.servlet;
import com.alibaba.fastjson.JSON;
import com.lingnan.dao.impl.NewsWorkersDaoImpl;
import com.lingnan.pojo.DataJson;
import com.lingnan.pojo.NewsWorker;
import com.lingnan.pojo.TableJson;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* @author :小邓
* @date :Created in 2022/7/4 14:58
* @description:单单
* @modified By:
* @version: 1.0
*/
@WebServlet("/ceshi")
public class ceshiServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
System.out.println(action);
String page = req.getParameter("page");
String limit = req.getParameter("limit");
System.out.println("第几页"+page+"几条"+limit);
if ( action.equals("mohu") ){
req.setCharacterEncoding("UTF8");
req.setCharacterEncoding("utf-8");//设置请求的编码格式为gb2312
resp.setContentType("text/html;charset=utf-8");//解决插入乱码问题顺序要放好
String eName = req.getParameter("eName");
System.out.println(eName);
List newsWorkers = new NewsWorkersDaoImpl().queryWorkByName(eName);
List workers = new ArrayList<>();
for ( int j = 0;j objectTableJson = new TableJson<>();
//封装json
objectTableJson.setCode(0);
objectTableJson.setMsg("OK");
// objectTableJson.setData(newsWorkers);
objectTableJson.setData(workers);
objectTableJson.setCount(workers.size());
System.out.println(objectTableJson);
String s = JSON.toJSONString(objectTableJson);//转换为json数据
PrintWriter writer = resp.getWriter();
writer.println(s);
// TableJson objectTableJson = new TableJson<>();
// //封装json
// objectTableJson.setCode(0);
// objectTableJson.setMsg("OK");
// objectTableJson.setData(newsWorkers);
// objectTableJson.setCount(newsWorkers.size());
// System.out.println(objectTableJson);
// String s = JSON.toJSONString(objectTableJson);//转换为json数据
// PrintWriter writer = resp.getWriter();
// writer.println(s);
}else {
req.setCharacterEncoding("UTF8");
req.setCharacterEncoding("utf-8");//设置请求的编码格式为gb2312
resp.setContentType("text/html;charset=utf-8");//解决插入乱码问题顺序要放好
//解决网页乱码的问题
List newsWorkers = new NewsWorkersDaoImpl().queryWork();
int size = newsWorkers.size();
System.out.println("数据:"+size);
List workers = new ArrayList<>();//新建一个数组来存放分页查询的数据
int x = Integer.parseInt(page) * Integer.parseInt(limit)-Integer.parseInt(limit);
System.out.println(x);
for(int i = x;(i objectTableJson = new TableJson<>();
//封装json
objectTableJson.setCode(0);
objectTableJson.setMsg("OK");
// objectTableJson.setData(newsWorkers);
objectTableJson.setData(workers);
objectTableJson.setCount(workers.size());
System.out.println(objectTableJson);
String s = JSON.toJSONString(objectTableJson);//转换为json数据
PrintWriter writer = resp.getWriter();
writer.println(s);//把json数据传输到网页中
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
五、封装json数据,不然 layui框架那边无法获取数据
package com.lingnan.pojo;
import lombok.Data;
import java.util.List;
import java.util.Map;
/**
* @author :小邓
* @date :Created in 2022/7/2 12:38
* @description:11
* @modified By:
* @version: 1.0
*/
@Data
public class TableJson {
private Integer code ;
private String msg ;
private List data;
private int count;
}
六、底层数据逻辑以及实体类
package com.lingnan.dao.impl;
import com.lingnan.dao.NewsWorkersDao;
import com.lingnan.pojo.NewsWorker;
import com.lingnan.util.DataBase;
import javax.servlet.http.HttpServlet;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* @author :小邓
* @date :Created in 2022/7/3 14:07
* @description:shitilei
* @modified By:
* @version: 1.0
*/
public class NewsWorkersDaoImpl implements NewsWorkersDao {
@Override
public List queryWork() {
List list = new ArrayList();
String sql = "select e_id, e_account, e_password, e_name, e_sex, e_education,d_name, e_position, e_idcard, " +
" e_phone, e_address, e_entrytion, e_role,flag" +
" from news_worker inner join news_department on news_worker.d_id = news_department.d_id";
// String sql="select * from news_worker";
ResultSet rs= DataBase.myQuery(sql, null);
try {
while (rs.next()){
//必须得放在里面,不然只是存储最后一条
NewsWorker allwork = new NewsWorker();
allwork.setEId(rs.getInt("e_id"));
// System.out.println(rs.getInt("e_id"));
allwork.setEAccount(rs.getString("e_account"));
allwork.setEPassword(rs.getString("e_password"));
allwork.setEName(rs.getString("e_name"));
allwork.setESex(rs.getString("e_sex"));
allwork.setEEducation(rs.getString("e_education"));
allwork.setDName(rs.getString("d_name"));
allwork.setEPosition(rs.getString("e_position"));
allwork.setEIdcard(rs.getString("e_idcard"));
allwork.setEPhone(rs.getString("e_phone"));
allwork.setEAddress(rs.getString("e_address"));
allwork.setEEntrytime(rs.getString("e_entrytion"));
allwork.setERole(rs.getInt("e_role"));
allwork.setFlag(rs.getInt("flag"));
list.add(allwork);
// System.out.println(allwork);
}
}
catch (SQLException e) {
e.printStackTrace();
}
return list;
}
@Override
public int insertWork(NewsWorker newsWorker) {
String sql = "insert into news_worker\n" +
" (e_id,e_account, e_password, e_name, e_sex,\n" +
" e_education, d_id, e_position, e_idcard,\n" +
" e_phone, e_address, e_entrytion) values (?,?,?,?,?,?,?,?,?,?,?,?)";
Object [] parms ={ newsWorker.getEId(),newsWorker.getEAccount(),newsWorker.getEPassword(),newsWorker.getEName(),
newsWorker.getESex(),newsWorker.getEEducation(),newsWorker.getDDid(),
newsWorker.getEPosition(),newsWorker.getEIdcard(),newsWorker.getEPhone(),
newsWorker.getEAddress(),newsWorker.getEEntrytime()};
return DataBase.executeUpdateAll(sql,parms);
}
@Override
public int deleteWork(String eId) {
String sql = "delete from news_worker where e_id=?";
Object [] parms = {eId};
return DataBase.executeUpdateAll(sql,parms);
}
@Override
public int deleteHuishouWork(int flag,String eId) {
String sql = "update news_worker set flag = ? where e_id = ?";
Object [] parms = {flag,eId};
return DataBase.executeUpdateAll(sql,parms);
}
@Override
public List queryWorkByName(String eName) {
List list = new ArrayList();
String sql = "select e_id, e_account, e_password, e_name, e_sex, e_education,d_name, e_position, e_idcard,e_phone, e_address, e_entrytion, e_role,flag from news_worker inner join news_department on news_worker.d_id = news_department.d_id where e_name like '%" + eName+ "%'";
// String sql = "select e_id, e_account, e_password, e_name, e_sex, e_education,d_name, e_position, e_idcard,e_phone, e_address, e_entrytion, e_role,flag from news_worker inner join news_department on news_worker.d_id = news_department.d_id where e_name like %?%";
System.out.println(sql);
// String sql = "select * from staff where sname like '%" + sname+ "%'";
// Object[] parms = {eName};
ResultSet rs= DataBase.myQuery(sql, null);
// ResultSet rs= DataBase.myQuery(sql, eName);
try {
while (rs.next()){
//必须得放在里面,不然只是存储最后一条
NewsWorker allwork = new NewsWorker();
allwork.setEId(rs.getInt("e_id"));
// System.out.println(rs.getInt("e_id"));
allwork.setEAccount(rs.getString("e_account"));
allwork.setEPassword(rs.getString("e_password"));
allwork.setEName(rs.getString("e_name"));
allwork.setESex(rs.getString("e_sex"));
allwork.setEEducation(rs.getString("e_education"));
allwork.setDName(rs.getString("d_name"));
allwork.setEPosition(rs.getString("e_position"));
allwork.setEIdcard(rs.getString("e_idcard"));
allwork.setEPhone(rs.getString("e_phone"));
allwork.setEAddress(rs.getString("e_address"));
allwork.setEEntrytime(rs.getString("e_entrytion"));
allwork.setERole(rs.getInt("e_role"));
allwork.setFlag(rs.getInt("flag"));
list.add(allwork);
// System.out.println(allwork);
}
}
catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
package com.lingnan.pojo;
import lombok.Data;
/**
* @author :小邓
* @date :Created in 2022/7/3 12:47
* @description:员工表实体类
* @modified By:
* @version: 1.0
*/
@Data
public class NewsWorker {
private int eId;//员工编号
//使用小辣椒会把首字母变成大写
private String eAccount;//员工账号
private String ePassword;//员工密码
private String eName;//员工姓名
private String eSex;//性别
private String eEducation;//学历
private int dDid;//部门id
private String dName;//部门名称
private String ePosition;//职称
private String eIdcard;//身份证号码
private String ePhone;//手机号码
private String eAddress;//家庭地址
private String eEntrytime;//入职时间
private int eRole;//权限
private int flag;//删除字段判断
}
你可能感兴趣的:(layui框架,layui,前端,大数据)