溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

layui+SSM的數(shù)據(jù)表的增刪改實例(利用彈框添加、修改)

發(fā)布時間:2020-09-04 19:49:58 來源:腳本之家 閱讀:1323 作者:delight_sl 欄目:web開發(fā)

本人前端知識相當(dāng)于小白,初學(xué)SSM時,了解了layui前端框架,所以開始研究了數(shù)據(jù)表的增刪改查,由于js、ajax知識不是很好,所以百度了相關(guān)ajax操作,用以借鑒。希望能幫助有需要的初學(xué)者,不喜勿噴,另外有相關(guān)不足,希望大家可以指出,謝謝!

注: 以下前端代碼都是利用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在線調(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í)行一個 table 實例
  table.render({
   elem: '#demo'
   , height: 420
   , url: '${ctx}/news/main/' //數(shù)據(jù)接口
   , 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: '新聞?wù)?, width: 180}
    , {field: 'author', title: '作者', width: 70}
    , {field: 'createDate', title: '創(chuàng)建時間', 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種層類型??蓚魅氲闹涤校?(信息框,默認)1(頁面層)2(iframe層)3(加載層)4(tips層)
      type: 1,
      title: "添加新聞信息",
      area: ['420px', '330px'],
      content: $("#popAddTest")//引用的彈出層的頁面層的方式加載修改界面表單
     });
     //動態(tài)向表傳遞賦值可以參看文章進行修改界面的更新前數(shù)據(jù)的顯示,當(dā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;//取得返回數(shù)據(jù)(Sting類型的字符串)的信息進行取值判斷
        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('請選擇一行');
     } else if (data.length > 1) {
      layer.msg('只能同時編輯一個');
     } else {
      layer.alert('編輯 [id]:' + checkStatus.data[0].id);
     }
     break;
    case 'delete':  /*批量刪除*/
     if (data.length === 0) {
      layer.msg('請選擇需要刪除的數(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;//取得返回數(shù)據(jù)(Sting類型的字符串)的信息進行取值判斷
        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="對應(yīng)的值"
   var data = obj.data //獲得當(dāng)前行數(shù)據(jù)
    , layEvent = obj.event; //獲得 lay-event 對應(yīng)的值
   if (layEvent === 'detail') {
    layer.msg('查看操作');
   } else if (layEvent === 'del') {
    /*layer.confirm('真的刪除行么', function(index){
     obj.del(); //刪除對應(yīng)行(tr)的DOM結(jié)構(gòu)
     layer.close(index);
     //向服務(wù)端發(fā)送刪除指令

    });*/

    layer.confirm('真的刪除行么', function (index) {
     obj.del(); //刪除對應(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;//取得返回數(shù)據(jù)(Sting類型的字符串)的信息進行取值判斷
       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種層類型??蓚魅氲闹涤校?(信息框,默認)1(頁面層)2(iframe層)3(加載層)4(tips層)
     type: 1,
     title: "修改新聞信息",
     area: ['420px', '330px'],
     content: $("#popUpdateTest")//引用的彈出層的頁面層的方式加載修改界面表單
    });
    //動態(tài)向表傳遞賦值可以參看文章進行修改界面的更新前數(shù)據(jù)的顯示,當(dā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;//取得返回數(shù)據(jù)(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
          });//修改成功修改表格數(shù)據(jù)不進行跳轉(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" >
 <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">新聞?wù)?lt;/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">新聞?wù)?lt;/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;
  }
 }

}


親測有效,希望大家提出不足!謝謝!另外后臺里面有一個時間轉(zhuǎn)換的類(DateUtil.formatDate()),前端有一個例如url: '${ctx}/news/update/',其中的${cxt}是一個指定的路徑,后臺寫了一個類,這些有需要的,可以看我的博客,謝謝!

以上這篇layui+SSM的數(shù)據(jù)表的增刪改實例(利用彈框添加、修改)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI