温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

layui+SSM的数据表的增删改实例(利用弹框添加、修改)

发布时间:2020-09-04 19:49:58 来源:脚本之家 阅读:1324 作者:delight_sl 栏目:web开发

本人前端知识相当于小白,初学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的数据表的增删改实例(利用弹框添加、修改)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI