您好,登錄后才能下訂單哦!
本人前端知識相當于小白,初學SSM時,了解了layui前端框架,所以開始研究了數據表的增刪改查,由于js、ajax知識不是很好,所以百度了相關ajax操作,用以借鑒。希望能幫助有需要的初學者,不喜勿噴,另外有相關不足,希望大家可以指出,謝謝!
注: 以下前端代碼都是利用layui的框架,后臺是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在線調試</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> <!-- 注意:如果你直接復制所有代碼到本地,上述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 //監聽Tab切換 element.on('tab(demo)', function (data) { layer.tips('切換了 ' + data.index + ':' + this.innerHTML, this, { tips: 1 }); }); //執行一個 table 實例 table.render({ elem: '#demo' , height: 420 , url: '${ctx}/news/main/' //數據接口 , title: '新聞表' , page: true //開啟分頁 , toolbar: 'default' //開啟工具欄,此處顯示默認圖標,可以自定義模板,詳見文檔 , totalRow: true //開啟合計行 , cols: [[ //表頭 {type: 'checkbox', fixed: 'left'} , {field: 'id', title: '新聞編號', width: 30, sort: true, fixed: 'left'} , {field: 'title', title: '新聞名稱', width: 180} , {field: 'summary', title: '新聞摘要', width: 180} , {field: 'author', title: '作者', width: 70} , {field: 'createDate', title: '創建時間', width: 100} , {fixed: 'right', width: 165, align: 'center', toolbar: '#barDemo'} ]] }); //監聽頭工具欄事件 table.on('toolbar(test)', function (obj) { var checkStatus = table.checkStatus(obj.config.id) , data = checkStatus.data; //獲取選中的數據 switch (obj.event) { case 'add': /*layer.msg('添加');*/ layer.open({ //layer提供了5種層類型。可傳入的值有:0(信息框,默認)1(頁面層)2(iframe層)3(加載層)4(tips層) type: 1, title: "添加新聞信息", area: ['420px', '330px'], content: $("#popAddTest")//引用的彈出層的頁面層的方式加載修改界面表單 }); //動態向表傳遞賦值可以參看文章進行修改界面的更新前數據的顯示,當然也是異步請求的要數據的修改數據的獲取 /*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;//取得返回數據(Sting類型的字符串)的信息進行取值判斷 if (returnCode == 200) { layer.closeAll('loading'); layer.load(2); layer.msg("添加成功", {icon: 6}); setTimeout(function () { location.reload();//刷新頁面 /* layer.closeAll();//關閉所有的彈出層*/ }, 1000 ); //加載層-風格 } else { layer.msg("添加失敗", {icon: 5}); } } }) return false;//false:阻止表單跳轉 true:表單跳轉 }) break; case 'update': if (data.length === 0) { layer.msg('請選擇一行'); } else if (data.length > 1) { layer.msg('只能同時編輯一個'); } else { layer.alert('編輯 [id]:' + checkStatus.data[0].id); } break; case 'delete': /*批量刪除*/ if (data.length === 0) { layer.msg('請選擇需要刪除的數據'); } 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;//取得返回數據(Sting類型的字符串)的信息進行取值判斷 if (returnCode == 200) { layer.closeAll('loading'); layer.load(2); layer.msg("刪除成功", {icon: 6}); setTimeout(function () { location.reload();//刷新頁面 /* layer.closeAll();//關閉所有的彈出層*/ }, 1000 ); //加載層-風格 } else { layer.msg("刪除失敗", {icon: 5}); } } }) return false;//false:阻止表單跳轉 true:表單跳轉 } break; } ; }); //監聽行工具事件 table.on('tool(test)', function (obj) { //注:tool 是工具條事件名,test 是 table 原始容器的屬性 lay-filter="對應的值" var data = obj.data //獲得當前行數據 , layEvent = obj.event; //獲得 lay-event 對應的值 if (layEvent === 'detail') { layer.msg('查看操作'); } else if (layEvent === 'del') { /*layer.confirm('真的刪除行么', function(index){ obj.del(); //刪除對應行(tr)的DOM結構 layer.close(index); //向服務端發送刪除指令 });*/ layer.confirm('真的刪除行么', function (index) { obj.del(); //刪除對應行(tr)的DOM結構 layer.close(index); //向服務端發送刪除指令 $.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;//取得返回數據(Sting類型的字符串)的信息進行取值判斷 if (returnCode == 200) { layer.closeAll('loading'); layer.load(2); layer.msg("刪除成功", {icon: 6}); setTimeout(function () { location.reload();//刷新頁面 /* layer.closeAll();//關閉所有的彈出層*/ }, 1000 ); //加載層-風格 } 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種層類型。可傳入的值有:0(信息框,默認)1(頁面層)2(iframe層)3(加載層)4(tips層) type: 1, title: "修改新聞信息", area: ['420px', '330px'], content: $("#popUpdateTest")//引用的彈出層的頁面層的方式加載修改界面表單 }); //動態向表傳遞賦值可以參看文章進行修改界面的更新前數據的顯示,當然也是異步請求的要數據的修改數據的獲取 /*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;//取得返回數據(Sting類型的字符串)的信息進行取值判斷 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 });//修改成功修改表格數據不進行跳轉 location.reload();//刷新頁面 /* layer.closeAll();//關閉所有的彈出層*/ }, 1000 ); //加載層-風格 } else { layer.msg("修改失敗", {icon: 5}); } } }) return false;//false:阻止表單跳轉 true:表單跳轉 }) } }); }); </script> <%--這里是彈出層表單(修改)--%> <div class="layui-row" id="popUpdateTest" > <div class="layui-col-md10"> <form class="layui-form layui-from-pane" action="" method=""> <div class="layui-form-item"><label class="layui-form-label">新聞標題</label> <div class="layui-input-block"><input type="text" name="newtitle" id="newtitle" autocomplete="off" placeholder="請輸入新聞標題" 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="newsummary" id="newsummary" autocomplete="off" placeholder="請輸入新聞編號" 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="請輸入作者" class="layui-input"> </div> </div> <div class="layui-form-item" > <div class="layui-input-block"> <button class="layui-btn layui-btn-submit " lay-submit="" lay-filter="submit11">確認修改</button> <button type="reset" class="layui-btn layui-btn-primary">重置</button> </div> </div> </form> </div> </div> <%--這里是彈出層表單(添加)--%> <div class="layui-row" id="popAddTest" > <div class="layui-col-md10"> <form class="layui-form layui-from-pane" action="" method=""> <div class="layui-form-item"><label class="layui-form-label">新聞標題</label> <div class="layui-input-block"><input type="text" name="newtitle" autocomplete="off" placeholder="請輸入新聞標題" 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="newsummary" autocomplete="off" placeholder="請輸入新聞編號" 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="請輸入作者" class="layui-input"> </div> </div> <div class="layui-form-item" > <div class="layui-input-block"> <button class="layui-btn layui-btn-submit " lay-submit="" lay-filter="submit12">確認添加</button> <button type="reset" class="layui-btn layui-btn-primary">重置</button> </div> </div> </form> </div> </div> </body> </html>
后臺:
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; } } }
親測有效,希望大家提出不足!謝謝!另外后臺里面有一個時間轉換的類(DateUtil.formatDate()),前端有一個例如url: '${ctx}/news/update/',其中的${cxt}是一個指定的路徑,后臺寫了一個類,這些有需要的,可以看我的博客,謝謝!
以上這篇layui+SSM的數據表的增刪改實例(利用彈框添加、修改)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。