Datatables学习(二)ajax获取数据

上一篇文章,讲解了datatables的基本创建,这一讲讲解datatables通过ajax异步获取数据

1、前提准备

以一个图书管理的表格为例,后台java代码就不细说了,这里主要讲解前端
数据库表结构如下:
这里写图片描述

实体类
package com.che.pri.entity;

import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="t_book")
public class Book {
    @Id
    @GeneratedValue
    private Integer id;
    @Column(length=100)
    private String name;
    @Column(length=50)
    private String author;

    private String date;

    private String image;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public String getImage() {
        return image;
    }
    public void setImage(String image) {
        this.image = image;
    }   

}

这里后台使用的是mybatis操作数据库

mapper层
package com.che.pri.mapper;

import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.che.pri.entity.Book;

public interface DataMapper {

    @Select("select * from t_book")
    List<Book> getData();

    @Delete("delete from t_book where id = #{id}")
    int delete(Book book);

    @Insert("insert into t_book(id,author,name,date) values(#{id},#{author},#{name},#{date})")
    int  insert(Book book);

    @Update("update t_book set author=#{author}, name=#{name},date=#{date} where id=#{id}")
    int update(Book book);
}
controller层
package com.che.pri.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.che.pri.bean.Data;
import com.che.pri.entity.Book;
import com.che.pri.mapper.DataMapper;

@Controller
@RequestMapping("/data")
public class DataController {

    @Autowired
    private DataMapper dataMapper;

    @ResponseBody
    @RequestMapping(value = "/list")
    public Object list() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Book> list = dataMapper.getData();
        System.out.println(list);
        map.put("data", dataMapper.getData());
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/delete/{id}")
    public Object delete(@PathVariable String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        Book book = new Book();
        book.setId(Integer.parseInt(id));
        int count = -1;
        count = dataMapper.delete(book);
        map.put("res", count);
        return map;
    }

    @ResponseBody
    @PostMapping(value = "/add")
    public Object add(Book book) {
        Map<String, Object> map = new HashMap<String, Object>();
        int count = -1;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        book.setDate(sdf.format(new Date()));
        count = dataMapper.insert(book);
        map.put("res", count);
        return map;
    }

    @ResponseBody
    @PostMapping(value = "/update")
    public Object update(Book book) {
        Map<String, Object> map = new HashMap<String, Object>();
        int count = -1;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        book.setDate(sdf.format(new Date()));
        count = dataMapper.update(book);
        map.put("res", count);
        return map;
    }
}

从代码中可以看出,后台一个提供了四个接口,list接口提供数据、delete接口删除数据、add接口添加数据、update接口修改数据,有了这个后台提供的增删改查四个接口后,就可以开始datatables的ajax操作了

2、修改表格表头结构
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js" ></script>
        <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js" type="text/javascript"></script>
    </head>
    <body>
          <table id="table_id" class="display">
            <thead>
                <tr>
                    <th class="text-center">序号</th>
                    <th class="text-center">编号</th>
                    <th class="text-center">作者</th>
                </tr>
            </thead>
            <tbody>

            </tbody>
        </table>

        <script>
            $(document).ready( function () {
                $('#table_id').DataTable();
            } );
        </script>
    </body>
</html>

注意:这里先给表格添加三列,另外两列,图片和添加时间后面再加上;其中 th 标签 中的 class="text-center" 为表头居中。此时,表格样式如下:
这里写图片描述

3、修改样式为中文

从上图可以看出,表格的文字显示为英文,现需要将其修改为中文显示
需要在js文件中添加如下代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js" ></script>
        <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js" type="text/javascript"></script>
    </head>
    <body>
          <table id="table_id" class="display">
            <thead>
                <tr>
                    <th class="text-center">序号</th>
                    <th class="text-center">编号</th>
                    <th class="text-center">作者</th>
                </tr>
            </thead>
            <tbody>

            </tbody>
        </table>

        <script>
            $(document).ready( function () {
                $('#table_id').DataTable({
                    language : {
                        "lengthMenu" : '每页显示<select>' + '<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":    "没有找到记录"

                    }
                });
            } );
        </script>
    </body>                             

表格如下;
这里写图片描述

4、添加ajax获取数据

代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js" ></script>
        <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js" type="text/javascript"></script>
    </head>
    <body>
          <table id="table_id" class="display">
            <thead>
                <tr>
                    <th class="text-center">序号</th>
                    <th class="text-center">编号</th>
                    <th class="text-center">作者</th>
                </tr>
            </thead>
            <tbody>

            </tbody>
        </table>

        <script>
            $(document).ready( function () {
                $('#table_id').DataTable({
                    language : {
                        "lengthMenu" : '每页显示<select>' + '<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":    "没有找到记录"

                    },
                    ajax : "http://localhost:8089/data/list",   
                    columns: [
                        {
                            "data": "id",
                            "name" : "id",
                            "sDefaultContent":"",  //默认空字符串
                            "sClass": "text-center"
                        },
                        {
                            "orderable" : false,
                            "data": "author",                   
                            'sClass': "text-center"                                 
                        },              
                        {
                            "orderable" : false,
                            "data": "name",             
                            'sClass': "text-center"                         
                         }                             
                    ]
                });
            } );
        </script>
    </body>
</html>

其中:ajax : "http://localhost:8089/data/list", 为获取数据;columns:为获取到的数据在表格中的样式 ;data 后对应的字符串为返回的json的键;http://localhost:8089/data/list 返回的json格式如下:
这里写图片描述
此时表格如下:
这里写图片描述
可以看见,列并没有居中,也就是说上边的 "sClass": "text-center" 并没有起作用,因为text-center,该属性属于bootatrap的属性,所以此时需要引入bootstrap的cssjs,后续开发会用到bootstrap的样式,代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
        <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js" ></script>
        <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js" type="text/javascript"></script>
        <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    </head>
    <body>
          <table id="table_id" class="display">
            <thead>
                <tr>
                    <th class="text-center">序号</th>
                    <th class="text-center">编号</th>
                    <th class="text-center">作者</th>
                </tr>
            </thead>
            <tbody>

            </tbody>
        </table>

        <script>
            $(document).ready( function () {
                $('#table_id').DataTable({
                    language : {
                        "lengthMenu" : '每页显示<select>' + '<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":    "没有找到记录"

                    },
                    ajax : "http://localhost:8089/data/list",   
                    columns: [
                        {
                            "data": "id",
                            "name" : "id",
                            "sDefaultContent":"",  //默认空字符串
                            "sClass": "text-center"
                        },
                        {
                            "orderable" : false,
                            "data": "author",                   
                            'sClass': "text-center"                                 
                        },              
                        {
                            "orderable" : false,
                            "data": "name",             
                            'sClass': "text-center"                         
                         }                             
                    ]
                });
            } );
        </script>
    </body>
</html>

此时表格如下:
这里写图片描述

5、添加datatables的bootatrap插件

通过以上的操作,基本完成了ajax获取数据,并修改字体为中文,但以上表格的样式依旧不是我们最终要求的;此时,需要引入datatables的bootatrap的样式插件,即dataTables.bootstrap.css文件和dataTables.bootstrap.js文件,同时注释掉jquery.dataTables.css文件,并将table标签的class属性display修改为bootstrap的<table>标签相关属性,具体代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <!--
        <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
        -->
        <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js" ></script>
        <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link href="http://cdn.datatables.net/plug-ins/28e7751dbec/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet" type="text/css"  />

        <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js" type="text/javascript"></script>
        <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
        <script src="http://cdn.datatables.net/plug-ins/28e7751dbec/integration/bootstrap/3/dataTables.bootstrap.js" type="text/javascript"></script>

    </head>
    <body>
          <table id="table_id" class="table table-bordered table-hover dataTable">
            <thead>
                <tr>
                    <th class="text-center">序号</th>
                    <th class="text-center">编号</th>
                    <th class="text-center">作者</th>
                </tr>
            </thead>
            <tbody>

            </tbody>
        </table>

        <script>
            $(document).ready( function () {
                $('#table_id').DataTable({
                    language : {
                        "lengthMenu" : '每页显示<select>' + '<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":    "没有找到记录"

                    },
                    ajax : "http://localhost:8089/data/list",   
                    columns: [
                        {
                            "data": "id",
                            "name" : "id",
                            "sDefaultContent":"",  //默认空字符串
                            "sClass": "text-center"
                        },
                        {
                            "orderable" : false,
                            "data": "author",                   
                            'sClass': "text-center"                                 
                        },              
                        {
                            "orderable" : false,
                            "data": "name",             
                            'sClass': "text-center"                         
                         }                             
                    ]
                });
            } );
        </script>
    </body>
</html>

表格样式如下:
这里写图片描述

此时,若想修改表格左上角每页显示多少条的样式,可以在 lengthMenu 对应的字符串中添加如下代码class="form-control input-xsmall",添加后的代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <!--
        <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
        -->
        <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js" ></script>
        <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link href="http://cdn.datatables.net/plug-ins/28e7751dbec/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet" type="text/css"  />

        <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js" type="text/javascript"></script>
        <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
        <script src="http://cdn.datatables.net/plug-ins/28e7751dbec/integration/bootstrap/3/dataTables.bootstrap.js" type="text/javascript"></script>

    </head>
    <body>
          <table id="table_id" class="table table-bordered table-hover dataTable">
            <thead>
                <tr>
                    <th class="text-center">序号</th>
                    <th class="text-center">编号</th>
                    <th class="text-center">作者</th>
                </tr>
            </thead>
            <tbody>

            </tbody>
        </table>

        <script>
            $(document).ready( function () {
                $('#table_id').DataTable({
                    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":    "没有找到记录"

                    },
                    ajax : "http://localhost:8089/data/list",   
                    columns: [
                        {
                            "data": "id",
                            "name" : "id",
                            "sDefaultContent":"",  //默认空字符串
                            "sClass": "text-center"
                        },
                        {
                            "orderable" : false,
                            "data": "author",                   
                            'sClass': "text-center"                                 
                        },              
                        {
                            "orderable" : false,
                            "data": "name",             
                            'sClass': "text-center"                         
                         }                             
                    ]
                });
            } );
        </script>
    </body>
</html>

此时表格如下:
这里写图片描述

到此,datatables的样式基本完成,下一篇讲解自定义按钮添加数据

猜你喜欢

转载自blog.csdn.net/wsjzzcbq/article/details/82348512
今日推荐