layui+SSM的數(shù)據(jù)表的增刪改實(shí)例(利用彈框添加、修改)
本人前端知識(shí)相當(dāng)于小白,初學(xué)SSM時(shí),了解了layui前端框架,所以開始研究了數(shù)據(jù)表的增刪改查,由于js、ajax知識(shí)不是很好,所以百度了相關(guān)ajax操作,用以借鑒。希望能幫助有需要的初學(xué)者,不喜勿噴,另外有相關(guān)不足,希望大家可以指出,謝謝!
注: 以下前端代碼都是利用layui的框架,后臺(tái)是SSM
前端:
<%--
Created by IntelliJ IDEA.
User: SL
Date: 2019/2/26
Time: 14:03
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<title>layui在線調(diào)試</title>
<link rel="stylesheet" href="${ctx}/static/layui/css/layui.css?t=1545041465443" rel="external nofollow" media="all">
<script src="${ctx}/static/jquery/jquery-3.3.1.js"></script>
<style>
body {
margin: 10px;
}
.demo-carousel {
height: 200px;
line-height: 200px;
text-align: center;
}
</style>
</head>
<body>
<table class="layui-hide" id="demo" lay-filter="test"></table>
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">查看</a>
<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 src="${ctx}/static/layui/layui.js?t=1545041465443" charset="utf-8"></script>
<!-- 注意:如果你直接復(fù)制所有代碼到本地,上述js路徑需要改成你本地的 -->
<script>
layui.config({
version: '1545041465443' //為了更新 js 緩存,可忽略
});
layui.use(['layer', 'table', 'element'], function () {
var layer = layui.layer //彈層
, table = layui.table //表格
, element = layui.element //元素操作
, form = layui.form
//監(jiān)聽Tab切換
element.on('tab(demo)', function (data) {
layer.tips('切換了 ' + data.index + ':' + this.innerHTML, this, {
tips: 1
});
});
//執(zhí)行一個(gè) table 實(shí)例
table.render({
elem: '#demo'
, height: 420
, url: '${ctx}/news/main/' //數(shù)據(jù)接口
, title: '新聞表'
, page: true //開啟分頁
, toolbar: 'default' //開啟工具欄,此處顯示默認(rèn)圖標(biāo),可以自定義模板,詳見文檔
, totalRow: true //開啟合計(jì)行
, cols: [[ //表頭
{type: 'checkbox', fixed: 'left'}
, {field: 'id', title: '新聞編號(hào)', width: 30, sort: true, fixed: 'left'}
, {field: 'title', title: '新聞名稱', width: 180}
, {field: 'summary', title: '新聞?wù)?, width: 180}
, {field: 'author', title: '作者', width: 70}
, {field: 'createDate', title: '創(chuàng)建時(shí)間', width: 100}
, {fixed: 'right', width: 165, align: 'center', toolbar: '#barDemo'}
]]
});
//監(jiān)聽頭工具欄事件
table.on('toolbar(test)', function (obj) {
var checkStatus = table.checkStatus(obj.config.id)
, data = checkStatus.data; //獲取選中的數(shù)據(jù)
switch (obj.event) {
case 'add':
/*layer.msg('添加');*/
layer.open({
//layer提供了5種層類型??蓚魅氲闹涤校?(信息框,默認(rèn))1(頁面層)2(iframe層)3(加載層)4(tips層)
type: 1,
title: "添加新聞信息",
area: ['420px', '330px'],
content: $("#popAddTest")//引用的彈出層的頁面層的方式加載修改界面表單
});
//動(dòng)態(tài)向表傳遞賦值可以參看文章進(jìn)行修改界面的更新前數(shù)據(jù)的顯示,當(dāng)然也是異步請(qǐng)求的要數(shù)據(jù)的修改數(shù)據(jù)的獲取
/*setFormValue(obj,data);*/
form.on('submit(submit12)', function (massage) {
$.ajax({
url: '${ctx}/news/add/',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
/*id: JSON.stringify(data.id),*/
id: data.id,
newtitle: massage.field.newtitle,
newsummary: massage.field.newsummary,
newauthor: massage.field.newauthor
}),
success: function (msg) {
var returnCode = msg.returnCode;//取得返回?cái)?shù)據(jù)(Sting類型的字符串)的信息進(jìn)行取值判斷
if (returnCode == 200) {
layer.closeAll('loading');
layer.load(2);
layer.msg("添加成功", {icon: 6});
setTimeout(function () {
location.reload();//刷新頁面
/* layer.closeAll();//關(guān)閉所有的彈出層*/
},
1000
);
//加載層-風(fēng)格
} else {
layer.msg("添加失敗", {icon: 5});
}
}
})
return false;//false:阻止表單跳轉(zhuǎn) true:表單跳轉(zhuǎn)
})
break;
case 'update':
if (data.length === 0) {
layer.msg('請(qǐng)選擇一行');
} else if (data.length > 1) {
layer.msg('只能同時(shí)編輯一個(gè)');
} else {
layer.alert('編輯 [id]:' + checkStatus.data[0].id);
}
break;
case 'delete': /*批量刪除*/
if (data.length === 0) {
layer.msg('請(qǐng)選擇需要?jiǎng)h除的數(shù)據(jù)');
} else {
/*layer.msg('刪除');*/
/* var checkStatus = table.checkStatus('demo');*/
var ids = "";
for(var i=0;i<data.length;i++){
ids += data[i].id+",";
}
alert(ids);
parent.layer.msg('刪除中...', {icon: 16,shade: 0.3,time:2000});
$.ajax({
url: '${ctx}/news/mulDelete/',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
/*id: JSON.stringify(data.id),*/
ids: ids
}),
success: function (msg) {
var returnCode = msg.returnCode;//取得返回?cái)?shù)據(jù)(Sting類型的字符串)的信息進(jìn)行取值判斷
if (returnCode == 200) {
layer.closeAll('loading');
layer.load(2);
layer.msg("刪除成功", {icon: 6});
setTimeout(function () {
location.reload();//刷新頁面
/* layer.closeAll();//關(guān)閉所有的彈出層*/
},
1000
);
//加載層-風(fēng)格
} else {
layer.msg("刪除失敗", {icon: 5});
}
}
})
return false;//false:阻止表單跳轉(zhuǎn) true:表單跳轉(zhuǎn)
}
break;
}
;
});
//監(jiān)聽行工具事件
table.on('tool(test)', function (obj) { //注:tool 是工具條事件名,test 是 table 原始容器的屬性 lay-filter="對(duì)應(yīng)的值"
var data = obj.data //獲得當(dāng)前行數(shù)據(jù)
, layEvent = obj.event; //獲得 lay-event 對(duì)應(yīng)的值
if (layEvent === 'detail') {
layer.msg('查看操作');
} else if (layEvent === 'del') {
/*layer.confirm('真的刪除行么', function(index){
obj.del(); //刪除對(duì)應(yīng)行(tr)的DOM結(jié)構(gòu)
layer.close(index);
//向服務(wù)端發(fā)送刪除指令
});*/
layer.confirm('真的刪除行么', function (index) {
obj.del(); //刪除對(duì)應(yīng)行(tr)的DOM結(jié)構(gòu)
layer.close(index);
//向服務(wù)端發(fā)送刪除指令
$.ajax({
url: '${ctx}/news/delete/'
, type: 'POST'
, data: "{\"id\":\"" + data.id + "\"}"
, dataType: 'json'
, contentType: "application/json; charset=utf-8"
, success: function (msg) {
var returnCode = msg.returnCode;//取得返回?cái)?shù)據(jù)(Sting類型的字符串)的信息進(jìn)行取值判斷
if (returnCode == 200) {
layer.closeAll('loading');
layer.load(2);
layer.msg("刪除成功", {icon: 6});
setTimeout(function () {
location.reload();//刷新頁面
/* layer.closeAll();//關(guān)閉所有的彈出層*/
},
1000
);
//加載層-風(fēng)格
} else {
layer.msg("刪除失敗", {icon: 5});
}
}
});
return false;
});
} else if (layEvent === 'edit') {
/* layer.prompt({
formType: 2
,value: data.summary
}, function(value, index){
obj.update({
summary: value
});
layer.close(index);
});*/
$("#newtitle").val(data.title);
$("#newsummary").val(data.summary);
$("#newauthor").val(data.author);
layer.open({
//layer提供了5種層類型??蓚魅氲闹涤校?(信息框,默認(rèn))1(頁面層)2(iframe層)3(加載層)4(tips層)
type: 1,
title: "修改新聞信息",
area: ['420px', '330px'],
content: $("#popUpdateTest")//引用的彈出層的頁面層的方式加載修改界面表單
});
//動(dòng)態(tài)向表傳遞賦值可以參看文章進(jìn)行修改界面的更新前數(shù)據(jù)的顯示,當(dāng)然也是異步請(qǐng)求的要數(shù)據(jù)的修改數(shù)據(jù)的獲取
/*setFormValue(obj,data);*/
form.on('submit(submit11)', function (massage) {
$.ajax({
url: '${ctx}/news/update/',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
/*id: JSON.stringify(data.id),*/
id: data.id,
newtitle: massage.field.newtitle,
newsummary: massage.field.newsummary,
newauthor: massage.field.newauthor
}),
success: function (msg) {
var returnCode = msg.returnCode;//取得返回?cái)?shù)據(jù)(Sting類型的字符串)的信息進(jìn)行取值判斷
if (returnCode == 200) {
layer.closeAll('loading');
layer.load(2);
layer.msg("修改成功", {icon: 6});
setTimeout(function () {
obj.update({
title: massage.field.newtitle,
summary: massage.field.newsummary,
author: massage.field.newauthor
});//修改成功修改表格數(shù)據(jù)不進(jìn)行跳轉(zhuǎn)
location.reload();//刷新頁面
/* layer.closeAll();//關(guān)閉所有的彈出層*/
},
1000
);
//加載層-風(fēng)格
} else {
layer.msg("修改失敗", {icon: 5});
}
}
})
return false;//false:阻止表單跳轉(zhuǎn) true:表單跳轉(zhuǎn)
})
}
});
});
</script>
<%--這里是彈出層表單(修改)--%>
<div class="layui-row" id="popUpdateTest" style="display:none;">
<div class="layui-col-md10">
<form class="layui-form layui-from-pane" action="" style="margin-top:20px" method="">
<div class="layui-form-item"><label class="layui-form-label">新聞標(biāo)題</label>
<div class="layui-input-block"><input type="text" name="newtitle" id="newtitle"
autocomplete="off" placeholder="請(qǐng)輸入新聞標(biāo)題" class="layui-input">
</div>
</div>
<div class="layui-form-item"><label class="layui-form-label">新聞?wù)?lt;/label>
<div class="layui-input-block"><input type="text" name="newsummary" id="newsummary"
autocomplete="off" placeholder="請(qǐng)輸入新聞編號(hào)" class="layui-input">
</div>
</div>
<div class="layui-form-item"><label class="layui-form-label">作者</label>
<div class="layui-input-block"><input type="text" name="newauthor" id="newauthor"
autocomplete="off" placeholder="請(qǐng)輸入作者" class="layui-input">
</div>
</div>
<div class="layui-form-item" style="margin-top:40px">
<div class="layui-input-block">
<button class="layui-btn layui-btn-submit " lay-submit="" lay-filter="submit11">確認(rèn)修改</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</form>
</div>
</div>
<%--這里是彈出層表單(添加)--%>
<div class="layui-row" id="popAddTest" style="display:none;">
<div class="layui-col-md10">
<form class="layui-form layui-from-pane" action="" style="margin-top:20px" method="">
<div class="layui-form-item"><label class="layui-form-label">新聞標(biāo)題</label>
<div class="layui-input-block"><input type="text" name="newtitle"
autocomplete="off" placeholder="請(qǐng)輸入新聞標(biāo)題" class="layui-input">
</div>
</div>
<div class="layui-form-item"><label class="layui-form-label">新聞?wù)?lt;/label>
<div class="layui-input-block"><input type="text" name="newsummary"
autocomplete="off" placeholder="請(qǐng)輸入新聞編號(hào)" class="layui-input">
</div>
</div>
<div class="layui-form-item"><label class="layui-form-label">作者</label>
<div class="layui-input-block"><input type="text" name="newauthor"
autocomplete="off" placeholder="請(qǐng)輸入作者" class="layui-input">
</div>
</div>
<div class="layui-form-item" style="margin-top:40px">
<div class="layui-input-block">
<button class="layui-btn layui-btn-submit " lay-submit="" lay-filter="submit12">確認(rèn)添加</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
后臺(tái):
package com.sl.controller;
import com.sl.model.NewsDetail;
import com.sl.service.NewsDetailService;
import com.sl.util.DateUtil;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/news")
public class NewsDetailController {
/*注入NewsDetailService*/
/**
*
*/
@Autowired
private NewsDetailService newsDetailService;
@RequestMapping("/main")
@ResponseBody
private Map<String, Object> queryAll() {
Map<String, Object> map = new HashMap<>();
List<NewsDetail> list = newsDetailService.queryAll();
int count = newsDetailService.queryAllCount();
map.put("data", list);
map.put("code", 0);
map.put("count", count);
return map;
}
@RequestMapping(value = "/delete", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
private Map<String, Object> deleteById(@RequestBody HashMap<String, String> map2) {
Map<String, Object> map = new HashMap<>();
int id = Integer.parseInt(map2.get("id"));
int row = newsDetailService.deleteById(id);
if (row == 1) {
List<NewsDetail> list = newsDetailService.queryAll();
int count = newsDetailService.queryAllCount();
map.put("data", list);
map.put("returnCode", "200");
map.put("count", count);
map.put("code", 0);
return map;
} else {
map.put("code", 1);
return map;
}
}
@RequestMapping(value = "/mulDelete", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public Map<String, Object> mulDelete(@RequestBody HashMap<String, String> map2){
Map<String, Object> map = new HashMap<>();
String ids = map2.get("ids");
String mulid[] = ids.split(",");
int row = 0;
for(int i=0; i<mulid.length; i++){
row = newsDetailService.mulDelete(mulid[i]);
}
if(row != 0){
List<NewsDetail> list = newsDetailService.queryAll();
int count = newsDetailService.queryAllCount();
map.put("code", 0);
map.put("data", list);
map.put("count", count);
map.put("returnCode", "200");
return map;
} else {
map.put("code", -1);
return map;
}
}
@RequestMapping(value = "/update", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public Map<String, Object> updateById(@RequestBody HashMap<String, String> map2) throws IOException {
Map<String, Object> map = new HashMap<>();
int id = Integer.parseInt(map2.get("id"));
String title = map2.get("newtitle");
String summary = map2.get("newsummary");
String author = map2.get("newauthor");
/*System.out.println(id+" "+title +" "+summary+" "+author);
System.out.println(1);
System.out.println(new Date());
System.out.println(DateUtil.getCurrentDateString());
System.out.println(2);*/
NewsDetail newsDetail = new NewsDetail();
newsDetail.setId(id);
newsDetail.setTitle(title);
newsDetail.setSummary(summary);
newsDetail.setAuthor(author);
newsDetail.setCreateDate(DateUtil.formatDate(new Date(), "yyyy-MM-dd HH-mm-ss"));
/*System.out.println(newsDetail.getCreateDate());
System.out.println(DateUtil.formatDate(new Date(), "yyyy-MM-dd HH-mm-ss"));*/
int row = newsDetailService.updateById(newsDetail);
if (row == 1) {
List<NewsDetail> list = newsDetailService.queryAll();
int count = newsDetailService.queryAllCount();
map.put("data", list);
map.put("count", count);
map.put("code", 0);
map.put("returnCode", "200");
return map;
} else {
map.put("code", 1);
return map;
}
}
@RequestMapping("/update2")
@ResponseBody
public Map<String, Object> update2(NewsDetail newsDetail) {
Map<String, Object> map = new HashMap<>();
/*newsDetail.setCreateDate(new Date());*/
int row = newsDetailService.updateById(newsDetail);
if (row == 1) {
List<NewsDetail> list = newsDetailService.queryAll();
int count = newsDetailService.queryAllCount();
map.put("data", list);
map.put("count", count);
map.put("code", 0);
return map;
} else {
map.put("code", 1);
return map;
}
}
@RequestMapping("/add")
@ResponseBody
public Map<String, Object> add(@RequestBody HashMap<String, String> map2) {
Map<String, Object> map = new HashMap<>();
String title = map2.get("newtitle");
String summary = map2.get("newsummary");
String author = map2.get("newauthor");
NewsDetail newsDetail = new NewsDetail();
newsDetail.setTitle(title);
newsDetail.setSummary(summary);
newsDetail.setAuthor(author);
newsDetail.setCreateDate(DateUtil.formatDate(new Date(), "yyyy-MM-dd HH-mm-ss"));
boolean row = newsDetailService.addNews(newsDetail);
if (row) {
List<NewsDetail> list = newsDetailService.queryAll();
int count = newsDetailService.queryAllCount();
map.put("data", list);
map.put("count", count);
map.put("returnCode", "200");
map.put("code", 0);
return map;
} else {
map.put("code", 1);
return map;
}
}
}
親測(cè)有效,希望大家提出不足!謝謝!另外后臺(tái)里面有一個(gè)時(shí)間轉(zhuǎn)換的類(DateUtil.formatDate()),前端有一個(gè)例如url: '${ctx}/news/update/',其中的${cxt}是一個(gè)指定的路徑,后臺(tái)寫了一個(gè)類,這些有需要的,可以看我的博客,謝謝!
以上這篇layui+SSM的數(shù)據(jù)表的增刪改實(shí)例(利用彈框添加、修改)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
JavaScript實(shí)現(xiàn)多個(gè)物體同時(shí)運(yùn)動(dòng)
這篇文章主要為大家詳細(xì)介紹了JavaScript實(shí)現(xiàn)多個(gè)物體同時(shí)運(yùn)動(dòng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03
解決bootstrap下拉菜單點(diǎn)擊立即隱藏bug的方法
本篇文章主要介紹了解決bootstrap下拉菜單點(diǎn)擊立即隱藏bug的方法,具有一定的參考價(jià)值,有興趣的可以了解一下2017-06-06
JavaScript禁止復(fù)制與粘貼的實(shí)現(xiàn)代碼
下面小編就為大家?guī)硪黄狫avaScript禁止復(fù)制與粘貼的實(shí)現(xiàn)代碼。小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考,一起跟隨小編過來看看吧2016-05-05
微信小程序?qū)崿F(xiàn)搜索功能并跳轉(zhuǎn)搜索結(jié)果頁面
這篇文章主要為大家詳細(xì)介紹了微信小程序?qū)崿F(xiàn)搜索功能并跳轉(zhuǎn)搜索結(jié)果頁面,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-05-05
原生JS實(shí)現(xiàn)首頁進(jìn)度加載動(dòng)畫
這篇文章主要為大家詳細(xì)介紹了原生JS實(shí)現(xiàn)首頁進(jìn)度加載動(dòng)畫,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09
基于JS實(shí)現(xiàn)簡(jiǎn)單滑塊拼圖游戲
本文通過實(shí)例代碼給大家介紹了JS實(shí)現(xiàn)簡(jiǎn)單滑塊拼圖游戲,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2019-10-10

