Datatables + Bootstrap 完整增删改查功能实现示例

Datatables样式 dataTables.bootstrap.min.js脚本以及相应的bootstrap.min.css、dataTables.bootstrap.min.css样式。,DataTables的Bootstrap集成还为DataTables中的分页控件提供了一个渲染器,以确保表的分页也由Bootstrap统一样式。此示例显示指定了order列类的DataTables,每一列的行数据都按照字符顺序排序。此示例指定了stripe类的DataTables,行使用不同的颜色交替显示。 阅读详情

前端使用 Datatables + Bootstrap + JQuery,后台使用 SpringBoot + Mybatis

 本代码旨在将 Datatables 的各个细节用法串联起来,因此前后端都没做非空验证。后台使用 SpringBoot + Mybatis,这里关于SpringBoot + Mybatis的整合就不详细说了,不懂的朋友可以参考:https://blog.csdn.net/wsjzzcbq/article/details/81563515

由于本文讲解的项目使用了本地静态资源,为方便大家学习,最后会将代码上传到码云,需要的朋友可以下载

 

效果演示如下图

效果图 1

 

效果图 2

 

1、数据库建表

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `user_addr` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `create_date` datetime(0) NULL DEFAULT NULL,
  `status` int(11) NULL DEFAULT NULL,
  `role_id` int(11) NULL DEFAULT NULL,
  PRIMARY KEY (`user_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 17 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '宋江', '山东省郓城县', '2020-08-01 15:52:00', 1, 2);
INSERT INTO `user` VALUES (3, '卢俊义', '北京大名府', '2020-08-02 15:52:25', 1, 2);
INSERT INTO `user` VALUES (4, '吴用', '山东省菏泽市郓城县车市村人', '2020-08-03 15:52:27', 1, 2);
INSERT INTO `user` VALUES (5, '公孙胜', '蓟州人氏', '2020-08-04 15:52:30', 1, 1);
INSERT INTO `user` VALUES (7, '关胜', '河东解良(今山西运城)人', '2020-08-05 17:04:08', 1, 1);
INSERT INTO `user` VALUES (8, '林冲', '东京(河南开封)人氏', '2020-07-27 17:14:32', 1, 1);
INSERT INTO `user` VALUES (9, '呼延灼', '并州太原(今属山西太原)', '2020-08-07 09:15:56', 1, 1);
INSERT INTO `user` VALUES (10, '花荣', '山东青州清风镇', '2020-08-07 09:17:17', 1, 1);
INSERT INTO `user` VALUES (11, '秦明', '山后开州', '2020-08-07 09:18:00', 1, 1);
INSERT INTO `user` VALUES (12, '柴进', '沧州人氏', '2020-08-07 09:18:42', 1, 1);
INSERT INTO `user` VALUES (13, '李应', '郓州人氏', '2020-08-07 09:19:13', 1, 1);
INSERT INTO `user` VALUES (14, '朱仝', '郓城县人氏', '2020-08-07 09:28:57', 1, 1);

 

2、引入 maven 的 pom 依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.datatables.demo</groupId>
    <artifactId>datatables-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>datatables-demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.7</version>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

3、配置 application.yml


server:
  port:  80

spring:
  datasource:
    url:  jdbc:mysql://192.168.0.110:3306/datatables_demo?useUnicode=true&characterEncoding=utf-8&useSSL=false
    driver-class-name:  com.mysql.cj.jdbc.Driver
    username:  root
    password:  123456

mybatis:
  mapper-locations:  classpath:mapper/*Mapper.xml
  config-location:  classpath:mapper/config/sqlMapConfig.xml

logging:
  level:
    com.datatables.demo.mapper: debug

 

4、实体类

package com.datatables.demo.bean;

import com.datatables.demo.common.page.Page;

import java.util.Date;

public class User extends Page {

    private Integer userId;

    private String userName;

    private String userAddr;

    private Date createDate;

    private Integer status;

    private Integer roleId;

    //日期范围查询条件
    private String date;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserAddr() {
        return userAddr;
    }

    public void setUserAddr(String userAddr) {
        this.userAddr = userAddr;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public Integer getRoleId() {
        return roleId;
    }

    public void setRoleId(Integer roleId) {
        this.roleId = roleId;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                ", userAddr='" + userAddr + '\'' +
                ", createDate=" + createDate +
                ", status=" + status +
                ", roleId=" + roleId +
                '}';
    }
}

 

5、公共实体类

datatables 分页实体类

package com.datatables.demo.common.page;

public class Page {

    private int draw;

    private int offset;

    private int pageSize;

    public int getDraw() {
        return draw;
    }

    public void setDraw(int draw) {
        this.draw = draw;
    }

    public int getOffset() {
        return offset;
    }

    public void setOffset(int offset) {
        this.offset = offset;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
}

 

datatables 分页返回实体类

package com.datatables.demo.common.res;

/**
 * datatables 接收实体类
 */
public class R {

    public R() {
    }

    public R(int draw, int recordsTotal, int recordsFiltered, Object data) {
        this.draw = draw;
        this.recordsTotal = recordsTotal;
        this.recordsFiltered = recordsFiltered;
        this.data = data;
    }

    private int draw;

    private int recordsTotal;

    private int recordsFiltered;

    private Object data;

    public int getDraw() {
        return draw;
    }

    public void setDraw(int draw) {
        this.draw = draw;
    }

    public int getRecordsTotal() {
        return recordsTotal;
    }

    public void setRecordsTotal(int recordsTotal) {
        this.recordsTotal = recordsTotal;
    }

    public int getRecordsFiltered() {
        return recordsFiltered;
    }

    public void setRecordsFiltered(int recordsFiltered) {
        this.recordsFiltered = recordsFiltered;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

 

6、mapper 层

package com.datatables.demo.mapper;

import com.datatables.demo.bean.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.session.RowBounds;
import java.util.List;
import java.util.Map;

@Mapper
public interface UserMapper {

    //查询分页数据
    List<User> getUserList(RowBounds rowBounds, Map<String, Object> map);

    //查询数据总条数
    int getUserListCount(RowBounds rowBounds, Map<String, Object> map);

    int insert(User user);

    int delete(Integer userId);

    User getById(Integer userId);

    int updateById(User user);
}

 

mapper 层 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.datatables.demo.mapper.UserMapper">
  <resultMap id="BaseResultMap" type="com.datatables.demo.bean.User">
    <id column="user_id" jdbcType="INTEGER" property="userId" />
    <result column="user_name" jdbcType="VARCHAR" property="userName" />
    <result column="user_addr" jdbcType="VARCHAR" property="userAddr" />
    <result column="create_date" jdbcType="TIMESTAMP" property="createDate" />
    <result column="status" jdbcType="INTEGER" property="status" />
    <result column="role_id" jdbcType="INTEGER" property="roleId" />
  </resultMap>

  <sql id="Base_Column_List">
    user_id, user_name, user_addr, role_id
  </sql>


  <!-- 查询分页数据 -->
  <select id="getUserList" parameterType="com.datatables.demo.bean.User" resultMap="BaseResultMap">
      select * from user where 1=1
      <if test="userName != null ">
        and INSTR(user_name, #{userName}) &gt; 0
      </if>
      <if test="userAddr != null ">
        and INSTR(user_addr, #{userAddr}) &gt; 0
      </if>
      <if test="status != null ">
        and status = #{status}
      </if>
      <if test="roleId != null ">
        and role_id = #{roleId}
      </if>
      <if test="startDate != null and endDate != null ">
          and DATE(create_date) BETWEEN  #{startDate} AND #{endDate}
      </if>
   </select>

  <!-- 查询数据总条数 -->
  <select id="getUserListCount" resultType="int">
      select count(*) from user where 1=1
      <if test="userName != null ">
        and INSTR(user_name, #{userName}) &gt; 0
      </if>
      <if test="userAddr != null ">
        and INSTR(user_addr, #{userAddr}) &gt; 0
      </if>
      <if test="status != null ">
        and status = #{status}
      </if>
      <if test="roleId != null ">
        and role_id = #{roleId}
      </if>
      <if test="startDate != null and endDate != null ">
          and DATE(create_date) BETWEEN  #{startDate} AND #{endDate}
      </if>
  </select>

  <insert id="insert" parameterType="com.datatables.demo.bean.User">
    insert into user (user_name, user_addr, status,
      role_id, create_date)
    values ( #{userName,jdbcType=VARCHAR}, #{userAddr,jdbcType=VARCHAR},
      #{status,jdbcType=INTEGER}, #{roleId,jdbcType=INTEGER}, #{createDate})
  </insert>

  <delete id="delete" parameterType="java.lang.Integer">
    delete from user where user_id = #{userId}
  </delete>

  <select id="getById" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select * from user where user_id = #{userId}
  </select>


  <update id="updateById" parameterType="com.datatables.demo.bean.User">
    update user
    set user_name = #{userName,jdbcType=VARCHAR},
      user_addr = #{userAddr,jdbcType=VARCHAR},
      status = #{status},
      role_id = #{roleId,jdbcType=INTEGER}
    where user_id = #{userId,jdbcType=INTEGER}
  </update>
</mapper>

 

7、service 层

package com.datatables.demo.service;

import com.datatables.demo.bean.User;
import com.datatables.demo.common.res.R;

public interface UserService {

    R getPageUserList(User user);

    int insert(User user);

    int delete(Integer userId);

    User getById(Integer userId);

    int updateById(User user);
}

 

serviceimpl 层

package com.datatables.demo.service.impl;

import com.datatables.demo.bean.User;
import com.datatables.demo.common.res.R;
import com.datatables.demo.mapper.UserMapper;
import com.datatables.demo.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public R getPageUserList(User user) {
        //查询条件
        Map<String, Object> searchCondition = new HashMap<String, Object>();

        if(StringUtils.isNotBlank(user.getUserName())) {
            searchCondition.put("userName", user.getUserName());
        }else {
            searchCondition.put("userName", null);
        }

        if(StringUtils.isNotBlank(user.getUserAddr())) {
            searchCondition.put("userAddr", user.getUserAddr());
        }else {
            searchCondition.put("userAddr", null);
        }

        if (-1 != user.getStatus()) {
            searchCondition.put("status", user.getStatus());
        }else {
            searchCondition.put("status", null);
        }

        if (-1 != user.getRoleId()) {
            searchCondition.put("roleId", user.getRoleId());
        }else {
            searchCondition.put("roleId", null);
        }

        if (StringUtils.isNotBlank(user.getDate())) {
            String[] dates = user.getDate().split(" - ");
            searchCondition.put("startDate", dates[0]);
            searchCondition.put("endDate", dates[1]);
        }else {
            searchCondition.put("startDate", null);
            searchCondition.put("endDate", null);
        }


        List<User> list = userMapper.getUserList(new RowBounds(user.getOffset(), user.getPageSize()), searchCondition);
        int count = userMapper.getUserListCount(new RowBounds(user.getOffset(), user.getPageSize()), searchCondition);

        R r = new R(user.getDraw(), count, count, list);
        return r;
    }

    @Override
    public int insert(User user) {
        //设置创建时间
        user.setCreateDate(new Date());
        return userMapper.insert(user);
    }

    @Override
    public int delete(Integer userId) {
        return userMapper.delete(userId);
    }

    @Override
    public User getById(Integer userId) {
        return userMapper.getById(userId);
    }

    @Override
    public int updateById(User user) {
        return userMapper.updateById(user);
    }
}

 

8、controller 层

package com.datatables.demo.controller;

import com.datatables.demo.bean.User;
import com.datatables.demo.common.res.R;
import com.datatables.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/list")
    public R list(User user) {
        R r = userService.getPageUserList(user);
        return r;
    }

    @PostMapping("/add")
    public String add(User user) {
        try {
            userService.insert(user);
            return "添加成功";
        }catch (Exception e){
            e.printStackTrace();
            return "添加失败";
        }
    }

    @GetMapping("/delete")
    public String delete(Integer userId) {
        try {
            userService.delete(userId);
            return "删除成功";
        }catch (Exception e){
            e.printStackTrace();
            return "删除失败";
        }
    }

    @GetMapping("/get")
    public User getById(Integer userId) {
        return userService.getById(userId);
    }

    @PostMapping("/update")
    public String update(User user) {
        try {
            userService.updateById(user);
            return "修改成功";
        }catch (Exception e){
            e.printStackTrace();
            return "修改失败";
        }
    }
}

 

9、springboot启动类

package com.datatables.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DatatablesDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DatatablesDemoApplication.class, args);
    }

}

 

10、前端 html 页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="/bootstrap/css/bootstrap.min.css"  rel="stylesheet" type="text/css"  />
    <link href="/DataTables/DataTables-1.10.18/css/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" type="text/css" media="all" href="/css/daterangepicker-bs3.css"/>
    <script type="text/javascript" src="/js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="/DataTables/DataTables-1.10.18/js/jquery.dataTables.min.js" ></script>
    <script type="text/javascript" src="/DataTables/DataTables-1.10.18/js/dataTables.bootstrap.js" ></script>
    <script type="text/javascript" src="/bootstrap/js/bootstrap.js"></script>
    <script type="text/javascript" src="/js/moment.js"></script>
    <script type="text/javascript" src="/js/daterangepicker.js"></script>
</head>
<body>
<div  class="row" style="margin-top:20px;">
    <div class="col-lg-12 col-lg-offset-1">
        <form class="form-inline">
            <div class="form-group">
                <input type="text" class="form-control" id="userName" placeholder="用户名">
            </div>

            <div class="form-group">
                <input type="text" class="form-control" id="userAddr" placeholder="用户地址">
            </div>

            <div class="form-group">
                <select id="status" class="form-control">
                    <option value="-1">状态</option>
                    <option value="1">通过</option>
                    <option value="0">驳回</option>
                </select>
            </div>

            <div class="form-group">
                <select id="roleId" class="form-control">
                    <option value="-1">角色</option>
                    <option value="1">普通用户</option>
                    <option value="2">管理员</option>
                </select>
            </div>

            <div class="form-group">
                <div class="controls">
                    <div class="input-prepend input-group">
                <span class="add-on input-group-addon"><i class="glyphicon glyphicon-calendar fa fa-calendar"></i></span>
                <input type="text" readonly style="width: 200px" name="reservation" id="reservation" class="form-control" value="" />
                    </div>
                </div>
            </div>






            <button type=button class="btn btn-success" id="searchButton"> 条 件 查 询 </button>
            <button type=button class="btn btn-warning" id="clearSearchButton"> 清 空 条 件 </button>
            <button type=button class="btn btn-primary" id="addButton" >添加用户</button>
        </form>


    </div>

    <div class="table-responsive col-lg-10 col-lg-offset-1" >
        <table id="table_id" class="table table-bordered table-hover">
            <thead>
            <tr>
                <th class="text-center">序号</th>
                <th class="text-center">ID</th>
                <th class="text-center">用户名</th>
                <th class="text-center">用户地址</th>
                <th class="text-center">创建时间</th>
                <th class="text-center">状态</th>
                <th class="text-center">角色名</th>
                <th class="text-center">操作</th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
</div>

<!-- 添加模态框 -->
<div id="addModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">添加用户</h4>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <input type="text" class="form-control" id="addUserName" placeholder="用户名">
                </div>

                <div class="form-group">
                    <input type="text" class="form-control" id="addUserAddr" placeholder="用户地址">
                </div>

                <div class="form-group">
                    <select id="addStatus" class="form-control">
                        <option value="-1">请选择状态</option>
                        <option value="1">通过</option>
                        <option value="0">驳回</option>
                    </select>
                </div>

                <div class="form-group">
                    <select id="addRole" class="form-control">
                        <option value="-1">请选择角色</option>
                        <option value="1">普通用户</option>
                        <option value="2">管理员</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="addUser()">确定</button>
            </div>
        </div>
    </div>
</div>

<!-- 修改模态框 -->
<div id="updateModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">修改用户</h4>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <input type="text" class="form-control" id="updateUserName" placeholder="用户名">
                </div>

                <div class="form-group">
                    <input type="text" class="form-control" id="updateUserAddr" placeholder="用户地址">
                </div>

                <div class="form-group">
                    <select id="updateStatus" class="form-control">
                        <option value="-1">请选择状态</option>
                        <option value="1">通过</option>
                        <option value="0">驳回</option>
                    </select>
                </div>

                <div class="form-group">
                    <select id="updateRole" class="form-control">
                        <option value="-1">请选择角色</option>
                        <option value="1">普通用户</option>
                        <option value="2">管理员</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="updateUser()">确定</button>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    var datatables_options = {
        language : {
            "lengthMenu" : '每页显示<select class="form-control input-xsmall">' + '<option value="10">10</option>'
                + '<option value="20">20</option>'
                + '<option value="30">30</option>'
                + '<option value="40">40</option>'
                + '<option value="50">50</option>' + '</select>条',
            "paginate" : {
                "first" : "首页",
                "last" : "尾页",
                "previous" : "上一页",
                "next" : "下一页"
            },
            "processing" : "加载中...",  //DataTables载入数据时,是否显示‘进度’提示
            "emptyTable" : "暂无数据",
            "info" : "共 _PAGES_ 页  _TOTAL_ 条数据  ",
            "infoEmpty" : "暂无数据",
            "emptyTable" : "暂无要处理的数据...",  //表格中无数据
            "search": "搜索:",
            "infoFiltered" : " —— 从  _MAX_ 条数据中筛选",
            "zeroRecords":    "没有找到记录"

        },
        ordering:  false,//排序显示控制
        searching : false,
        paging: true,//开启分页
        processing : true,
        serverSide : true,//是否开启服务器模式
        ajax : {
            url: '/user/list',
            type: 'post',
            cache: false,
            data : function(d){
                var user = {};
                user.userName = $("#userName").val();
                user.userAddr = $("#userAddr").val();
                user.status = $("#status").val();
                user.roleId = $("#roleId").val();
                user.date = $("#reservation").val();
                user.pageSize = d.length;
                user.draw = d.draw;
                user.offset = d.start;
                return user;
            },
            dataFilter : function(json){

                json = JSON.parse(json);

                var returnData = {};
                returnData.draw = json.draw;
                returnData.recordsTotal = json.recordsTotal;  //返回数据全部记录
                returnData.recordsFiltered = json.recordsFiltered;  //后台不实现过滤功能,每次查询均视作全部结果
                returnData.data = json.data;  //返回的数据列表
                return JSON.stringify(returnData); //这几个参数都是datatable需要的,必须要

            }
        },
        columns: [
            {
                "data" : null,
                "orderable" : false,
                "sClass": "text-center"
            },
            {
                "data": "userId",
                "name" : "id",
                "orderable" : true,
                "sDefaultContent":"",  //默认空字符串
                "sClass": "text-center"
            },
            {
                "orderable" : false,
                "data": "userName",
                'sClass': "text-center"
            },
            {
                "orderable" : false,
                "data": "userAddr",
                'sClass': "text-center"
            },
            {
                "orderable" : false,
                "data": "createDate",
                'sClass': "text-center",
                "render": function ChangeDateFormat(date) {
                    var dateee = new Date(date).toJSON();
                    return new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
                }
            },
            {
                "orderable" : false,
                "data": "status",
                'sClass': "text-center",
                'render': function (data, type,row,meta){
                    var status = row.status
                    var str  = ''
                    if(status == 1){
                        str = '通过'
                    }
                    if(status == 0){
                        str = '驳回'
                    }
                    return str

                }
            },
            {
                "orderable" : false,
                "data": "roleId",
                'sClass': "text-center",
                'render': function (data, type,row,meta){
                    var roleId = row.roleId
                    var str  = ''
                    if(roleId == 1){
                        str = '普通用户'
                    }
                    if(roleId == 2){
                        str = '管理员'
                    }
                    return str

                }
            },
            {
                "orderable" : false,
                "targets" : 2,//操作按钮目标列
                "data" : null,
                "sWidth" :"250px",
                'sClass': "text-center",
                "render" : function(data, type,row,meta) {
                    var id = '"' + row.userId + '"';
                    var html = "";
                    html += "<button onclick='edit("+ id +")'  style='margin-right:10px;' class='up btn btn-warning '>编辑</button>"
                    html += "<a href='javascript:void(0);'   onclick='deleteData("+id+ ")'  class='down btn btn-danger '> 删除</a>"
                    return html;
                }
            }

        ],
        fnDrawCallback :function () {
            let api = this.api();
            let startIndex = api.context[0]._iDisplayStart;//获取本页开始的条数
            api.column(0).nodes().each(function(cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    };





    var firstTable;
    firstTable = $('#table_id').DataTable(datatables_options);


    $("#addButton").click(function(){
        $("#addModal").modal()
    })

    function addUser() {
        $.ajax({
            type:"post",
            url:"/user/add",
            async:true,
            data:{
                userName: $("#addUserName").val(),
                userAddr: $("#addUserAddr").val(),
                status: $("#addStatus").val(),
                roleId: $("#addRole").val()
            },
            success:function(res){
                // 刷新表格数据,分页信息不会重置
                firstTable.ajax.reload(null,false);
                //清空添加表单数据
                clearAddData();
                alert(res)
            }
        });
    }

    function clearAddData(){
        $("#addUserName").val('')
        $("#addUserAddr").val('')
        $("#addStatus").val(-1)
        $("#addRole").val(-1)
    }

    /**
     * 删除
     */
    function deleteData(id) {
        $.ajax({
            type:"get",
            url:"/user/delete",
            async:true,
            data:{
                userId: id
            },
            success:function(res){
                // 刷新表格数据,分页信息不会重置
                firstTable.ajax.reload(null,false);

                alert(res)
            }
        });
    }

    //全局用户id
    var userId;
    function edit(id) {
        $.ajax({
            type:"get",
            url:"/user/get",
            async:true,
            data:{
                userId: id
            },
            success:function(res){
                //设置回显用户数据
                userId = res.userId //赋值给全局id,方便修改后使用
                $("#updateUserName").val(res.userName)
                $("#updateUserAddr").val(res.userAddr)
                $("#updateStatus").val(res.status)
                $("#updateRole").val(res.roleId)
                $("#updateModal").modal()
            }
        });
    }

    function updateUser() {
        $.ajax({
            type:"post",
            url:"/user/update",
            async:true,
            data:{
                userId: userId,
                userName: $("#updateUserName").val(),
                userAddr: $("#updateUserAddr").val(),
                status: $("#updateStatus").val(),
                roleId: $("#updateRole").val()
            },
            success:function(res){
                // 刷新表格数据,分页信息不会重置
                firstTable.ajax.reload(null,false);

                alert(res)
            }
        });
    }

    $("#searchButton").click(function(){
        firstTable.ajax.reload(null,false);
        firstTable.draw(false);

    });

    $("#clearSearchButton").click(function(){
        $("#userName").val('');
        $("#userAddr").val('');
        $("#status").val(-1);
        $("#roleId").val(-1);
        $("#reservation").val('')
    });

    //日期范围选择器
    $('#reservation').daterangepicker(null, function(start, end, label) {
        console.log(start.toISOString(), end.toISOString(), label);
    });
</script>


</body>
</html>

 

 

码云地址:https://gitee.com/wsjzzcbq/datatables-demo

 

 

MATLAB表格增强:利用DataTables实现交互式数据报告 在数据分析和科学计算领域,静态表格是展示结果的常见形式,但其缺乏交互性限制了数据探索的深度。通过理解HTML文档结构及JavaScript动态渲染原理,可以突破这一限制。前端技术栈如jQuery与DataTables库,能够为静态表格注入排序、筛选、分页等交互功能,从而极大提升数据可读性与分析效率。这种技术方案的核心价值在于,它允许用户在无需切换工具或编写复杂代码的情况下,直接在生成的报告中与数据进行动态交互。在工程实践中,这尤其适用于需要向非技术背景的决策者展示结果,或将分析结果集成到内部工具的场景。本文 阅读详情

相关推荐

Bootstrap+DataTables后端排序分页详解

网上找了很多文章,都没有统一的写完前后端Bootstrap+DataTables到底是怎么运行好的,因此在折腾了好久后,把运行好的贴出来以作备份参考. 首先贴前台的table <table id="example1" class="table table-bordered table-hover table-striped"> <thead> <tr&...

svygh123的专栏 1657

BootStrap-DataTables教程

本文3个部分一:什么是DataTablesDatatables是一款jquery表格插件。它是一个高度灵活的工具,可以将任何HTML表格添加高级的交互功能。 分页,即时搜索和排序 几乎支持任何数据源:DOM, javascript, Ajax 和 服务器处理 支持不同主题 DataTables, jQuery UI, Bootstrap, Foundation 各式各样的扩展: Editor

ajavaer的博客 1万+

基于Bootstrap3和Datatables的Servlet SQLite3数据管理示例

本文还有配套的精品资源,点击获取 简介:本项目演示了一个结合Bootstrap3、Datatables、Servlet和SQLite3的后台数据管理系统。Bootstrap3用于构建响应式的用户界面,Datatables展示动态数据和实现前端分页功能,Servlet处理后端数据操作如增删改查,并将结果通过JSON格式返回,SQLite3作为轻量级数据库存储数据。通过Mave...

weixin_32836713的博客 1580

Bootstrap的Datatable详解

$('#scenerytable').dataTable({ "sDom": "r>>", "bProcessing": true,//显示正在处理 "bServerSide": true,//延迟加载 "bPaginate": true,//显示(使用)分页器

mingtianhaiyouwo的博客 3万+

WebVB6中Datatables与Bootstrap4集成实现数据库应用

在Web开发中,将数据以表格形式展示是常见需求之一。Datatables是一个功能丰富的JavaScript库,它能将HTML表格转换成具有排序、搜索、分页等高级功能的动态表格。虽然WebVB6技术相对老旧,但它的广泛使用基础要求我们探索在该平台上集成现代Web功能的方法。Datatables提供了强大的接口,使其可以与WebVB6兼容,从而提升用户体验和数据交互效率。Bootstrap4是目前最流行和广泛使用的前端框架之一。它提供了大量的预制组件和工具类,允许开发者快速搭建响应式的网站界面。

weixin_35752645的博客 691

bootstrap dataTables使用方法

bootstrap dataTables使用方法 datatables常用API 文档整理很方便

基于SpringMVC+Bootstrap+DataTables实现表格服务端分页、模糊查询

前言基于SpringMVC+Bootstrap+DataTables实现数据表格服务端分页、模糊查询,页面异步刷新。说明:sp:message标签是使用了SpringMVC国际化效果DataTable表格关键字查询自定义关键字查询,非DataTable Search 代码HTML代码查询条件代码<!-- 查询、添加、批量删除、导出、刷新 --> <div class="row-fluid">

Jason 2万+

OGG工具实现MySQL同步到Oracle数据库

OGG工具实现MySQL同步数据到Oracle

Mrzhou的博客 1691

【3】案例:Bootstrap + jQuery及DataTables + Python Flask框架开发 - 账号管理模块(增删改查)零基础入门版

一、效果展示 二、目标 实现管理系统模块 - 账号管理的增删改查功能。 三、技术选型 样式:Bootstrap 前端:jQuery +DataTables 后端:Python Flask 四、前端关键代码 1、左侧菜单导航nav样式,详细说明参考我的文章 【2】案例:Bootstrap 开发 - navs 左侧菜单,使用iframe 嵌入*.html实现动态切换页面_YYDataV的博客-CSDN博客 2、使用$("selector").load(url) 实现在父页..

记录项目交付的日常 3524

ARIMA模型的R实现

1.模型简介 ARIMA模型,全称差分自回归移动平均模型。可以看作是差分运算和ARMA模型的结合。主要是针对具有线性趋势的非平稳的时间序列,来进行建模预测。 ARIMA模型的形式如下: Φ(B)∇

heirenmin的博客 1万+

Qt绘图实战:用QGraphicsItem实现可拖拽箭头连接(附完整代码)

本文详细介绍了如何使用Qt的QGraphicsItem框架实现一个功能完备的可拖拽箭头连接组件。通过核心代码示例,讲解了如何创建自定义图形项、实现智能吸附、碰撞检测以及实时拖拽编辑路径,为构建流程图、拓扑图等专业图形编辑器提供了完整的解决方案。

m2n3b4v5c6的博客 630

datatables+springmvc+bootstrap实现分页

  datatables是前端的一个实现分页的插件,支持主流的浏览器,非常好用。datatables网址:http://www.datatables.club/ 里面有许多的样式,还支持bootstrap。这里用datatables+springmvc+bootstrap做了一个样例。   效果图: 数据是从服务器获取的,因为数据库不大,所有数据都通过json全部都传到前台了,datat...

BushRo 3230

ZYNQ新手必看:你的PS端DDR和QSPI配置真的对了吗?从原理到实操的避雷指南

本文深入解析ZYNQ PS端外设配置的关键要点,特别是DDR匹配和QSPI时钟优化的实战技巧。通过详细案例和配置清单,帮助开发者避免常见错误,确保系统稳定性和启动可靠性。适合ZYNQ新手和需要优化最小系统的开发者参考。

weixin_28675839的博客 449

datatables增删改查php,DataTables实现增删改查(1.10版本)

这段时间项目需要做个APP的管理后台,运维人员用的,简单的增删改查,于是想到了dataTable,下面简单记录下个人在使用过程中的一些难点,顺带一些没有解决的问题,将随着项目的进展,慢慢解决。先看一下插件的页面效果: 对于一款前端插件,要考虑这样一个问题,相比不用插件和其他插件,这款插件的优势值不值得自己花精力去学习并掌握这个插件。如果仅仅作为表格的载体,其实有很多插件可以选择。我更看重的是它的编...

weixin_42511206的博客 527

【NLP】文献翻译4——CH-SIMS:中文多模态情感分析数据集与细粒度的模态注释

CH-SIMS: A Chinese Multimodal Sentiment Analysis Dataset with Fine-grained Annotations of Modality摘要1. 介绍2. 相关工作2.1 多模态数据集2.2 多模态情感分析2.3 多任务学习3. CH-SIMS 数据集3.1 数据获取3.2 标注3.3 特征提取4. 多模式多任务学习框架4.1 单模态子网4.2 特征融合网络4.3 优化目标5. 实验5.1 基准5.2 实验的细节5.3 结果和讨论5.3.1 与

YoungSeng's Blog 1万+

从零开始:Ubuntu 24.04 LTS + Win11双系统安装教程

本文将简单直白介绍如何从零开始在同一台电脑上安装 Ubuntu 24.04 LTS 和 Windows 11,你可以在需要进行专业开发或运维工作时,轻松切换到 Ubuntu,享受其带来的高效与自由;而在日常学习生活和娱乐休闲时,依然可以无缝使用熟悉的 Windows 环境。

萑澈的博客 8139

datatables和bootstrap

bootstrap是对HTML的表格做简单的样式设置,可以改变行宽行高和背景颜色。bootstrap的主要作用是在于原色的排版且可以自适应屏幕大小。而datatables更专注于给表格增加一些衍生功能,如翻页,搜索和排序。它整合了bootstrap对于表格的操作。 datatables注重dom的理解与操作,因为功能插件都是根据dom来定位添加 使用步骤: 1 导入js和css的包,2 初始化 $(document).ready( function () { $('#table_id_exa..

weixin_59263248的博客 1330

【OpenClaw从入门到精通】第45篇:Skill供应链安全——如何识别并避开恶意技能插件?(2026实测版)

随着OpenClaw生态爆发式增长,全球Skills总量近75万个,日均新增2.1万个,但恶意/问题插件已超600个,数十万用户受影响。本文基于奇安信威胁报告及360安全实践,拆解恶意技能的五大核心特征,提出"安装前三步法"安全审查流程,详解安全技能来源白名单与定期审计方案,并深度解析360龙虾Skill安全超市的分级认证机制。读者可掌握从技能筛选、安装审查到术后审计的全流程安全防护手段,通过实操命令与案例演示,零成本构建Skill供应链安全防线,避免遭遇私钥窃取、资产损失等安全事件。

专注于人工智能、软件开发、工控自动化、工厂数字化及智能化等领域,希望和大家共同进步! 566

Datatables+Bootstrap

http://sandbox.runjs.cn/show/thwac3ec  运行效果 DOCTYPE html> html lang="en"> head> meta charset="utf-8"> title>bootstrap datatable demotitle> meta name="viewport" content="width=device-w

mingtianhaiyouwo的博客 2611

自然语言处理在智能客服系统中的应用

引言与背景 1.1 书籍的目的和内容概述 《自然语言处理在智能客服系统中的应用》旨在探讨自然语言处理(NLP)技术在智能客服系统中的应用,帮助读者理解NLP的核心概念及其在解决实际业务问题中的关键作用。随着人工智能技术的快速发展,自然语言处理成为构建智能客服系统的核心模块之一。本书将深入解析NLP

AI天才研究院 976

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

Datatables设置默认排序方式

  在 BootStrap 中使用了 Datatables 插件,这个是真的舒服,表格一系列操作都省了,只需要简单copy一些样式过来就好了。   当然,Datatables是一款jquery表格插件,对表格操作有很强大的功能,看看下面这个示例就知道,实际上自己啥代码也没写,功能就都有了,自己配置一下参数就行了。   本文主要是讲述Datatables的列排序问题,直接上代码。 $(do...

渣渣的夏天 7967

贝叶斯统计 [韦来生编]

贝叶斯(Bayes)统计是近几十年来迅速发展起来的数理统计的一个重要分支。贝叶斯方法与经典统计方法的主要不同之处是进行统计推断时除了利用样本信息外,还要利用参数的先验信息,因此可以提高统计推断或统计决策的效果。它在经济、金融、生物、医学、自然科学和社会科学等许多领域具有广泛的应用。贝叶斯方法的研究已渗透到了统计学的几乎所有领域。作者在给中国科学技术大学概率论与数理统计专业本科生开设的“数理统计”课程中有一章专门讲授“贝叶斯方法和统计决策理论”,近十年来也给中国科学技术大学概率统计专业研究生开设过几次“贝叶斯分析”课。本书是在对过去讲稿的内容作了适当的增减和调整的基础上完成的。  本书共分六章。第1章是绪论,介绍了贝叶斯统计的若干基本概念,同时对必要的数理统计的基础知识有重点地作了回顾。第二章介绍了确定先验分布的若干可供选择的方法。第三章介绍了几类常见统计模型参数的后验分布的主要结果和计算方法。第四章和第五章分别介绍了“贝叶斯统计推断”和“贝叶斯统计决策”的内容。第六章介绍了贝叶斯统计计算的若干方法,包括蒙特卡洛方法和马尔可夫链蒙特卡洛(MCMC)方法以及相关统计软件的简介。本书的每一章附右大量的例题和习题,书末附有常用的几个表格和部分习题解答供读者查用。  大约可在54学时内讲授本书的第1章至第六章的主要内容,教师可根据学时需要选讲本书第1章至第六章的部分内容。书中标“*”号的章节可略去不讲,留给读者作为阅读材料。第六章例题中的R代码和部分例题的数据文件等可从作者个人主页下载。  作者在编写本书的过程中参考了J.O.Berger教授的《统计决策论及贝叶斯分析》和茆诗松教授编写的《贝叶斯统计》等书中的一些内容,以及《贝叶斯分析》一书中由张伟平博士编写的有关贝叶斯统计计算的一些内容。在此表示衷心感谢。  本书编写准备过程中,中国科学技术大学统计与金融系的几个研究生帮助完成了本书部分中文的录入和排版,作者对他们的辛勤工作表示真诚的感谢。高等教育出版社为本书的出版给予了大力支持。在此一并致谢。

前端控件JQuery Datatables使用——常用功能初始化

本文用于自己记录,忘记时可以用来回顾。点击这里进入JQuerydatatable官网API地址  JQuery Datatables初始化 个人比较喜欢JQueryDatatables的Bootstrap4风格,所以文章以Bootstrap4风格为例。 JQueryDatatable的初始化很简单,按照官网的举例说明,只要如下几个JS和CSS文件即可: 1、jquery-3.3.1.min.js,当然高版本的JS也是可以的 2、jque...

Bingo 3482

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Datatables + Bootstrap 组合基础示例 1

緣由 最近在研究 Datatables 這個 jQuery 表格插件,其功能詳見 Datatables 官網。 在次僅分享下我在學習過程中所做的一些示例。 示例 1 Datatables + Bootstrap 组合基础示例 1 基本功能:分頁、排序、過濾。 貌似引用 runjs 失敗了,不好...

119

DataTables增删改查(二)

这篇文章主要记录针对表格的常用操作,增删改查。涉及的内容包括需要的文件、如何定义操作按钮、一些控件如何交互插件链接Benefits 针对普通需求,不需要写编辑页面,插件自动生成 自动适配的表格的风格,是页面看起来比较舒服 Requirements css bootstrap.min.css dataTables.bootstrap.min.css buttons.bootstrap.min.c

yuan487639的博客 2985

SpringBoot+PageHelper+Bootstrap+Thymeleaf 实现分页功能

本文针对那种想要快速实现功能,而不是研究原理的,那你就直接复制我的东西,运行就好。如果想深入学习的同学请另行百度。 第一种Spring Boot + Thymeleaf 使用PageHelper实现分页 这种实际上就是单独使用分页插件来实现分页功能。好处是,分页条你可以自行排版,不受页面约束。(前端使用的是thymeleaf) 我使用的是spring boot 2.1.11.RELEA...

phubing 1万+

解决datatables在bootstrap模态框modal中表头缩小问题

最近项目中需要在弹出框中集成datatables,整个项目框架用的bootstrap,用户点击按钮时,弹出模态框,模态框中的datatables自动加载数据。模态框代码:我调整了模态框的宽度&lt;div class="modal fade" id="record_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" ..

qq_26920153的博客 3176
上一篇: datatables 报错 Uncaught TypeError: Cannot read property ‘DT_RowId‘ of null
下一篇: springboot 整合mybatis plus
悟世君子
博客等级 码龄8年 3351粉丝 406原创
评论 5
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悟世君子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值