【ssm框架】ssm框架处理静态资源文件,实现jQuery+Bootstrap表格数据增删改查

ssm框架处理静态资源文件,实现jQuery+Bootstrap表格数据增删改查
在之前文章的 搭建ssm框架 【ssm框架】从0开始搭建ssm框架(idea版本)

处理静态文件

(1)在之前ssm框架的基础上,添加静态资源文件
在这里插入图片描述

(2)找到springmvc的配置文件 ,在里面加入下面配置。 使用SpringMVC下的静态资源处理类,在容器中加载形成Bean

    <!--    加载静态资源文件-->
    <mvc:resources location="/static/css/" mapping="/static/css/**"/>
    <mvc:resources location="/static/js/" mapping="/static/js/**"/>
    <mvc:resources location="/static/" mapping="/static/**"/>

引入资源文件

jQuery

官网: https://www.jq22.com/jquery-info122/

Bootstrap

官网: https://v4.bootcss.com/

toastr

toastr是一款轻量级的消息提示插件,基于JQuery,使用简单方便,外观大气漂亮。
官网: https://codeseven.github.io/toastr/

封装组件提示框 js

(function ($) {

    window.Ewin = function () {
        var html = '<div id="[Id]" class="modal fade" role="dialog" aria-labelledby="modalLabel">' +
            '<div class="modal-dialog modal-sm">' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>' +
            '<h4 class="modal-title" id="modalLabel">[Title]</h4>' +
            '</div>' +
            '<div class="modal-body">' +
            '<p>[Message]</p>' +
            '</div>' +
            '<div class="modal-footer">' +
            '<button type="button" class="btn btn-default cancel" data-dismiss="modal">[BtnCancel]</button>' +
            '<button type="button" class="btn btn-primary ok" data-dismiss="modal">[BtnOk]</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';


        var dialogdHtml = '<div id="[Id]" class="modal fade" role="dialog" aria-labelledby="modalLabel">' +
            '<div class="modal-dialog">' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>' +
            '<h4 class="modal-title" id="modalLabel">[Title]</h4>' +
            '</div>' +
            '<div class="modal-body">' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        var reg = new RegExp("\\[([^\\[\\]]*?)\\]", 'igm');
        var generateId = function () {
            var date = new Date();
            return 'mdl' + date.valueOf();
        }
        var init = function (options) {
            options = $.extend({}, {
                title: "操作提示",
                message: "提示内容",
                btnok: "确定",
                btncl: "取消",
                width: 200,
                auto: false
            }, options || {});
            var modalId = generateId();
            var content = html.replace(reg, function (node, key) {
                return {
                    Id: modalId,
                    Title: options.title,
                    Message: options.message,
                    BtnOk: options.btnok,
                    BtnCancel: options.btncl
                }[key];
            });
            $('body').append(content);
            $('#' + modalId).modal({
                width: options.width,
                backdrop: 'static'
            });
            $('#' + modalId).on('hide.bs.modal', function (e) {
                $('body').find('#' + modalId).remove();
            });
            return modalId;
        }

        return {
            alert: function (options) {
                if (typeof options == 'string') {
                    options = {
                        message: options
                    };
                }
                var id = init(options);
                var modal = $('#' + id);
                modal.find('.ok').removeClass('btn-success').addClass('btn-primary');
                modal.find('.cancel').hide();

                return {
                    id: id,
                    on: function (callback) {
                        if (callback && callback instanceof Function) {
                            modal.find('.ok').click(function () {
                                callback(true);
                            });
                        }
                    },
                    hide: function (callback) {
                        if (callback && callback instanceof Function) {
                            modal.on('hide.bs.modal', function (e) {
                                callback(e);
                            });
                        }
                    }
                };
            },
            confirm: function (options) {
                var id = init(options);
                var modal = $('#' + id);
                modal.find('.ok').removeClass('btn-primary').addClass('btn-success');
                modal.find('.cancel').show();
                return {
                    id: id,
                    on: function (callback) {
                        if (callback && callback instanceof Function) {
                            modal.find('.ok').click(function () {
                                callback(true);
                            });
                            modal.find('.cancel').click(function () {
                                callback(false);
                            });
                        }
                    },
                    hide: function (callback) {
                        if (callback && callback instanceof Function) {
                            modal.on('hide.bs.modal', function (e) {
                                callback(e);
                            });
                        }
                    }
                };
            },
            dialog: function (options) {
                options = $.extend({}, {
                    title: 'title',
                    url: '',
                    width: 800,
                    height: 550,
                    onReady: function () {
                    },
                    onShown: function (e) {
                    }
                }, options || {});
                var modalId = generateId();

                var content = dialogdHtml.replace(reg, function (node, key) {
                    return {
                        Id: modalId,
                        Title: options.title
                    }[key];
                });
                $('body').append(content);
                var target = $('#' + modalId);
                target.find('.modal-body').load(options.url);
                if (options.onReady())
                    options.onReady.call(target);
                target.modal();
                target.on('shown.bs.modal', function (e) {
                    if (options.onReady(e))
                        options.onReady.call(target, e);
                });
                target.on('hide.bs.modal', function (e) {
                    $('body').find(target).remove();
                });
            }
        }
    }();
})(jQuery);

在static中导入相关资源文件,在index.html中引入相关css和js

在这里插入图片描述

   <link rel="stylesheet" type="text/css" href="static/css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="static/css/toastr.min.css">
    <script src="static/js/jquery-3.5.1.js" type="text/javascript"></script>
    <script src="static/js/bootstrap.js" type="text/javascript"></script>
    <script src="static/js/confirm.js" type="text/javascript"></script>
    <script src="static/js/toastr.min.js" type="text/javascript"></script>

员工的增删改查

controller
package com.beiluo.controller;

import com.beiluo.pojo.Employee;
import com.beiluo.service.EmployeeService;

import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @RequestMapping(value = "/getEmployeePage/page/{pageNo}", method = RequestMethod.GET)
    @ResponseBody
    public PageInfo<Employee> getEmployeePage(@PathVariable("pageNo") Integer pageNo, Model model) {
        //获取员工的分页信息
        PageInfo<Employee> page = employeeService.getEmployeePage(pageNo);
        return page;
    }

    @RequestMapping(value = "/getAllEmployee", method = RequestMethod.GET)
    @ResponseBody
    public List<Employee> getAllEmployee() {
        //查询所有的员工信息
        List<Employee> list = employeeService.getAllEmployee();
        return list;
    }

    @RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
    @ResponseBody
    public int addEmployee(Employee employee) {
        //查询所有的员工信息
        int num = employeeService.addEmployee(employee);
        return num;
    }

    @RequestMapping(value = "/updateEmployee", method = RequestMethod.POST)
    @ResponseBody
    public int updateEmployee(Employee employee) {
        int num = employeeService.updateEmployee(employee);
        return num;
    }

    @RequestMapping(value = "/deleteEmployee", method = RequestMethod.POST)
    @ResponseBody
    public int deleteEmployee(Integer empId) {
        int num = employeeService.deleteEmployeeById(empId);
        return num;
    }


    @RequestMapping(value = "/getByEmpId/{empId}", method = RequestMethod.GET)
    @ResponseBody
    private Map<String, Object> getByEmpId(HttpServletRequest request, @PathVariable("empId") int empId) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        modelMap.put("empId", empId);
        return modelMap;
    }

    @RequestMapping(value = "/getById", method = RequestMethod.GET)
    @ResponseBody
    private Map<String, Object> getById(HttpServletRequest request, @RequestParam(value = "id", required = true) int id) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        modelMap.put("id", id);
        return modelMap;
    }

}

pojo
package com.beiluo.pojo;

/**
 * 员工类
 *
 * @author beiluo
 */
public class Employee {

    private Integer empId;

    private String empName;

    private Integer age;

    private String gender;

    private String email;

    public Employee() {
    }

    public Employee(Integer empId, String empName, Integer age, String gender, String email) {
        this.empId = empId;
        this.empName = empName;
        this.age = age;
        this.gender = gender;
        this.email = email;
    }

    public Integer getEmpId() {
        return empId;
    }

    public void setEmpId(Integer empId) {
        this.empId = empId;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "empId=" + empId +
                ", empName='" + empName + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

service

package com.beiluo.service;

import com.beiluo.pojo.Employee;
import org.apache.ibatis.annotations.Param;
import com.github.pagehelper.PageInfo;

import java.util.List;

/**
 * Service
 */
public interface EmployeeService {

    /**
     * 查询所有的员工信息
     *
     * @return
     */
    List<Employee> getAllEmployee();

    /**
     * 获取员工的分页信息
     *
     * @param pageNum
     * @return
     */
    PageInfo<Employee> getEmployeePage(Integer pageNum);

    //增加
    int addEmployee(Employee employee);

    //删除
    int deleteEmployeeById(Integer empId);

    //更新
    int updateEmployee(Employee employee);

    //查询
    Employee queryEmployeeById(Integer empId);
}

serviceImpl

package com.beiluo.service.impl;

import com.beiluo.mapper.EmployeeMapper;
import com.beiluo.pojo.Employee;
import com.beiluo.service.EmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public List<Employee> getAllEmployee() {
        return employeeMapper.getAllEmployee();
    }

    @Override
    public PageInfo<Employee> getEmployeePage(Integer pageNum) {
        //开启分页功能
        PageHelper.startPage(pageNum, 4);
        //查询所有的员工信息
        List<Employee> list = employeeMapper.getAllEmployee();
        //获取分页相关数据
        PageInfo<Employee> page = new PageInfo<>(list, 5);
        return page;
    }

    /**
     * @param employee
     * @return
     */
    @Override
    public int addEmployee(Employee employee) {
        return employeeMapper.addEmployee(employee);
    }

    /**
     * @param empId
     * @return
     */
    @Override
    public int deleteEmployeeById(Integer empId) {
        return employeeMapper.deleteEmployeeById(empId);
    }

    /**
     * @param employee
     * @return
     */
    @Override
    public int updateEmployee(Employee employee) {
        return employeeMapper.updateEmployee(employee);
    }

    /**
     * @param empId
     * @return
     */
    @Override
    public Employee queryEmployeeById(Integer empId) {
        return employeeMapper.queryEmployeeById(empId);
    }
}

mapper

EmployeeMapper

package com.beiluo.mapper;

import com.beiluo.pojo.Employee;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 *
 */
public interface EmployeeMapper {

    /**
     * 查询所有的员工信息
     *
     * @return
     */
    List<Employee> getAllEmployee();

    //增加
    int addEmployee(Employee employee);

    //删除
    int deleteEmployeeById(@Param("empId") Integer empId);

    //更新
    int updateEmployee(Employee employee);

    //查询
    Employee queryEmployeeById(@Param("empId") Integer empId);

}

mybatis xml配置

EmployeeMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.beiluo.mapper.EmployeeMapper">

    <!--List<Employee> getAllEmployee();-->
    <select id="getAllEmployee" resultType="Employee">
        select *
        from t_emp
    </select>

    <!--   mysql支持自增主键,自增主键值的获取,mybatis也是利用statement.getGenreatedKeys();
    useGeneratedKeys="true";使用自增主键获取主键值策略;
    keyProperty;指定对应的主键属性,也就是mybatis获取到主键值以后,将这个值封装给javaBean的哪个属性-->
    <insert id="addEmployee" parameterType="Employee" useGeneratedKeys="true" keyProperty="empId">
        insert into t_emp (emp_name, age, gender, email)
        values (#{empName}, #{age}, #{gender}, #{email});
    </insert>

    <update id="updateEmployee" parameterType="Employee">
        update t_emp
        set emp_id  = #{empId},
            emp_name= #{empName},
            age= #{age},
            gender= #{gender},
            email= #{email}
        where emp_id = #{empId}

    </update>

    <delete id="deleteEmployeeById" parameterType="Integer">
        delete
        from t_emp
        where emp_id = #{empId}
    </delete>

</mapper>

前端请求

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <!-- 手机端 -->
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
    <title>首页</title>
    <!--    <link rel="stylesheet" type="text/css" href="../../static/css/bootstrap.css">
        <link rel="stylesheet" type="text/css" href="../../static/css/toastr.min.css">
        <script src="../../static/js/jquery-3.5.1.js" type="text/javascript"></script>
        <script src="../../static/js/bootstrap.js" type="text/javascript"></script>
        <script src="../../static/js/confirm.js" type="text/javascript"></script>
        <script src="../../static/js/toastr.min.js" type="text/javascript"></script>-->
    <link rel="stylesheet" type="text/css" href="static/css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="static/css/toastr.min.css">

    <script src="static/js/jquery-3.5.1.js" type="text/javascript"></script>
    <script src="static/js/bootstrap.js" type="text/javascript"></script>
    <script src="static/js/confirm.js" type="text/javascript"></script>
    <script src="static/js/toastr.min.js" type="text/javascript"></script>



    <style type="text/css">
        .navbar-collapse {
            /* 弹性布局中的一个属性 */
            /* 前提套用container固定容器*/
            flex-grow: 0;
        }
    </style>
</head>
<body>
<!-- 导航条 -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container">
        <!-- 标题-->
        <a class="navbar-brand" href="#">员工信息管理</a>
        <!-- data-toggle="collapse"控制折叠切换效果
            data-target="#navbarNav"根据id找到指定的折叠容器-->
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
                aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <!-- active选中  disabled禁用-->
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav">
                <li class="nav-item active home-button">
                    <a class="nav-link" href="#">首页 <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">登录</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">注册</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link disabled">我的</a>
                </li>
            </ul>
        </div>


    </div>
</nav>


<!--修改-->
<div class="modal fade" id="myUpdateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
     aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="myModalLabel">修改用户</h4>
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

            </div>
            <div class="modal-body">
                <form class="form-horizontal" role="form">
                    <!--                    //隐藏域-->
                    <input type="hidden" id="empId"/>
                    <div class="form-group">
                        <label for="empName" class="col-sm-2 control-label">姓名</label>
                        <div class="col-sm-8">
                            <input type="text" class="form-control" id="empName" placeholder="请输入姓名">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email" class="col-sm-2 control-label">邮箱</label>
                        <div class="col-sm-8">
                            <input type="text" class="form-control" id="email" placeholder="请输入邮箱">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="age" class="col-sm-2 control-label">年龄</label>
                        <div class="col-sm-8">
                            <input type="number" class="form-control" id="age" min="1" max="99"
                                   placeholder="请输入年龄">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="gender" class="col-sm-2 control-label">性别</label>
                        <div class="col-sm-8">
                            <div class="radio">
                                <label>
                                    <input type="radio" name="gender" id="man" value="true" checked></label>
                                <label>
                                    <input type="radio" name="gender" id="woman" value="false"></label>
                            </div>


                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="updateBtn">提交更改</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>


<!--新增-->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="myModalLabelAdd">新增</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>

            </div>
            <div class="modal-body">
                <form>


                    <div class="form-group has-success has-feedback">
                        <label class="control-label" for="inputSuccess1">工作</label>
                        <input type="text" class="form-control" id="inputSuccess1" placeholder="工作" >
                        <span class="help-block">你输入的信息是正确的</span>
                        <span class="glyphiconglyphicon-ok form-control-feedback"></span>
                    </div>


                    <div class="form-group">
                        <label for="empNameAdd">姓名</label>
                        <input type="text" name="empNameAdd" class="form-control" id="empNameAdd"
                               placeholder="姓名">
                    </div>
                    <div class="form-group">
                        <label for="ageAdd">年龄</label>
                        <input type="text" name="ageAdd" class="form-control" id="ageAdd"
                               placeholder="年龄">
                    </div>

                    <div class="form-group">
                        <label for="genderAdd">性别</label>
                        <label>
                            <input type="radio" name="genderAdd" id="gender_man" value="true" checked></label>
                        <label>
                            <input type="radio" name="genderAdd" id="gender_woman" value="false"></label>
                    </div>

                    <div class="form-group">
                        <label for="emailAdd">邮箱</label>
                        <input type="text" name="emailAdd" class="form-control" id="emailAdd" placeholder="邮箱">
                    </div>
                </form>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><span
                        class="glyphicon glyphicon-remove" aria-hidden="true"></span>关闭
                </button>
                <button type="button" id="btn_submit" class="btn btn-primary" data-dismiss="modal"><span
                        class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span>保存
                </button>
            </div>
        </div>
    </div>
</div>

<div id="userList">

</div>


<script>
    $(document).ready(function () {

        //初始化列表
        getList();
     
    });


    function getList() {
        $.ajax({
            type: "get",
            url: "http://localhost:8080/ssm/employee/getAllEmployee", //请求路径
            // data: JSON.stringify({name: "John", id: "1001"}),
            // contentType: "application/json",
            dataType: "json",   // 预期返回一个 json 类型数据
            success: function (result) {
                console.log(result);

                //判断是否存在
                if (result == null || result.length < 1) {
                    //给div元素赋值 html()
                    $("#userList").html(" <button class=\"btn btn-success btn-xs\" οnclick=\"openAddDialog()\"> <span class= \"glyphicon glyphicon-plus\"> </span> 添加</button><h3 class='text-center'>暂无信息!</h3>")
                } else {
                    //准备table
                    var table = $('<table class="table table-striped table-bordered table-hover"></table>');
                    //说明
                    var caption = $('<caption >用户列表</caption>');
                    //将caption标签设置到table对象中
                    table.append(caption);
                    //创建表头 thead
                    var thead = $(' <thead> <tr> <th>编号</th> <th>姓名</th> <th>邮箱</th> <th>年龄</th> <th>性别</th> <th>操作 &nbsp;&nbsp;&nbsp;&nbsp <button class="btn btn-success btn-xs" οnclick="openAddDialog()"> <span class= "glyphicon glyphicon-plus"> </span> 添加</button></th>  </tr></thead>');

                    //将表头设置到table对象中
                    table.append(thead);

                    //解析ajax请求获取到的数据
                    //准备tboby对象
                    var tbody = $('<tbody></tbody>');
                    //遍历数组,拼接tr对象
                    for (var i = 0; i < result.length; i++) {
                        var user = result[i];
                        var sex = "男";
                        if (user.gender==2) {
                            sex = "女";
                        }
                        //拼接tr对象
                        var tr = '<tr id="tr_' + user.empId + '"> <td>' + user.empId + '</td> <td>' + user.empName + '</td> <td>' + user.email + '</td>';
                        tr += '<td>' + user.age + '</td> <td>' + user.gender + '</td>';
                        tr += '<td><button class="btn btn-warning btn-xs" οnclick="openUpdateDialog(' + user.empId + ')"> <span class= "glyphicon glyphicon-pencil"> </span>修改</button>';
                        tr += '<button class="btn btn-danger btn-xs" οnclick="deleteUser(' + user.empId + ')"><span class="glyphicon glyphicon-trash"></span>删除</button></td></tr>';
                        //tr+='<button class="btn btn-danger btn-xs" οnclick="deleteUser2(this)"><span class="glyphicon glyphicon-trash"></span>删除</button></td></tr>';
                        //将tr对象追加到tbody中
                        tbody.append(tr);
                    }
                    //将tbody对象追加到table中
                    table.append(tbody);

                    //将table对象设置到指点div中
                    $("#userList").append(table);
                }

            }
        });

    }


    function deleteUser(empId) {
        Ewin.confirm({message: "确认要删除选择的数据吗?"}).on(function (e) {
            if (!e) {
                return;
            }
            $.ajax({
                type: "post",
                data: {empId: empId},
                url: "http://localhost:8080/ssm/employee/deleteEmployee",
                success: function (data, status) {
                    if (status == "success") {
                        toastr.success('提交数据成功');
                    }
                },
                error: function () {
                    toastr.error('Error');
                },
                complete: function () {
                }
            });
        });

    }


    function openUpdateDialog(empId) {
        //得到要修改的tr对象
        var tr = $("#tr_" + empId);
        //得到tr对象的所有子元素
        var tds = tr.children();
        //eq(index)匹配指定下标的元素
        //姓名
        var empName = tds.eq(1).text();
        var email = tds.eq(2).text();
        var age = tds.eq(3).text();
        var gender = tds.eq(4).text();
        //赋值给模态框
        $("#empName").val(empName);
        $("#email").val(email);
        $("#age").val(age);
        if (gender == "男") {
            $("#man").prop("checked", true);
        } else {
            $("#woman").prop("checked", true);
        }
        //将编号设置到隐藏域中
        $("#empId").val(empId);

        $("#myUpdateModal").modal("show")
    }


    //修改用户信息
    $("#updateBtn").click(function () {
        //得到模态框中的表单元素的值
        var empId = $("#empId").val();
        var empName = $("#empName").val();
        var email = $("#email").val();
        var age = $("#age").val();
        var gender = "男";
        //判断女是否被选中
        if ($("#woman").prop("checked")) {
            gender = "女";
        }
        //修改单元格的值
        var tr = $("#tr_" + empId);
        tr.children().eq(1).text(empName);
        tr.children().eq(2).text(email);
        tr.children().eq(3).text(age);
        tr.children().eq(4).text(gender);
        //关闭
        $("#myUpdateModal").modal("hide");


        var emp = {
            empId: empId,
            empName: empName,
            age: age,
            gender: gender,
            email: email
        }


        $.ajax({
            type: "post",
            url: "http://localhost:8080/ssm/employee/updateEmployee",
            data: emp,
            success: function (data, status) {
                console.log(data, status);
                //提示成功
                toastr.success('修改成功');
            },
            error: function () {
                toastr.error('Error');
            },
            complete: function () {

            }

        });

    })


    /**
     * 保存
     */
    $("#btn_submit").click(function () {
        //1.
        // var empId = $("#empIdAdd").val();
        var empName = $("#empNameAdd").val();
        var email = $("#emailAdd").val();
        var age = $("#ageAdd").val();
        var gender = "男";
        if ($("#genderAdd").prop("checked")) {
            gender = "女";
        }
        //2.
        /*   if (isStrEmpty(empId)) {
               $("#addMsg").html("编号不能为空");
               return;
           }*/

        if (isStrEmpty(empName)) {
            $("#addMsg").html("姓名不能为空");
            return;
        }

        if (isStrEmpty(email)) {
            $("#addMsg").html("邮箱不能为空");
            return;
        }

        if (isStrEmpty(age)) {
            $("#addMsg").html("年龄不能为空");
            return;
        }

        var emp = {
            empName: empName,
            age: age,
            gender: gender,
            email: email
        }

        console.log("emp", emp);

        $.ajax({
            type: "post",
            url: "http://localhost:8080/ssm/employee/addEmployee",
            data: emp,
            success: function (data, status) {
                console.log(data, status);
                toastr.success('提交数据成功');

            },
            error: function () {
                toastr.error('Error');
            },
            complete: function () {

            }

        });


        //3.
        var tr = '<tr id="tr_' + empId + '"> <td>' + empId + '</td> <td>' + empName + '</td> <td>' + email + '</td>';
        tr += '<td>' + age + '</td> <td>' + gender + '</td>';
        tr += '<td><button class="btn btn-warning btn-xs" οnclick="openUpdateDialog(' + empId + ')"> <span class= "glyphicon glyphicon-pencil"> </span>修改</button>';
        tr += '<button class="btn btn-danger btn-xs" οnclick="deleteUser(' + empId + ')"><span class="glyphicon glyphicon-trash"></span>删除</button></td></tr>';
        //tr+='<button class="btn btn-danger btn-xs" οnclick="deleteUser2(this)"><span class="glyphicon glyphicon-trash"></span>删除</button></td></tr>';
        //将tr对象追加到tbody中
        $("tbody").append(tr);

        //清空模态框中元素
        $("#addForm")[0].reset();

        //关闭模态框
        $("#myAddModal").modal("hide");

    });


    /**
     * 判断当前对象的值是否为空
     * @param obj 需要判断的对象
     * @returns {boolean} true对象为空
     */
    function isObjEmpty(obj) {
        return obj === null || obj === 'undefined' || obj === 'null' || obj === undefined;
    }

    /**
     * 判断当前字符串是否为空
     * @param str 需要判断的字符串
     * @return {boolean} true内容为空
     */
    function isStrEmpty(str) {
        return isObjEmpty(str) || str.length === 0 || String(str).trim() === '';
    }


    function openAddDialog() {
        $("#myModalLabelAdd").text("新增");
        $('#myModal').modal();
    }


</script>
</body>
</html>

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值