dataTables的学习笔记 -- 未开启服务器数据模式

 

官方网站:http://www.datatables.net/

(1)未开启服务器数据模式(即"bServerSide" : false),数据会从后台直接全部获取,然后在前台全部渲染,分页是框架自己完成的。

(2)开启服务器数据模式(即"bServerSide" : true),数据从后台查询,接着在前台将查询到的所有数据全部渲染到一页上,所以需要在后台分页后传到前台。

bServerSide的值默认为false。

建议:在数据量非常大的情况下建议在后台分页,即开启服务器数据模式。

 本次以未开启服务器数据模式为例

 1、jsp页面

<div class="adv-table">
     <table class="display table table-bordered" id="userList">
     </table>
</div>

2、js代码

$(document).ready(function() {

    /*
     * Initialse DataTables, with no sorting on the 'details' column
     */
    var oTable = $('#userList').dataTable( {
        "bLengthChange": true, //允许改变每页显示的数据条数, 默认为true
        "bFilter": true, //开启搜索功能, 默认为true
        "bInfo" : true,     //开启Datatables信息显示
        "bPaginate" : true, //允许表格分页, 默认为true
        
        "bProcessing": true, //开启读取服务器数据时显示正在加载中
        //"bServerSide": true, //开启服务器模式
        "iDisplayLength": 5,//每页显示15条数据
        
        // Ajax地址
        "sAjaxSource": contextPath + "/user/getUserList?time=" + new Date().getTime(),
        "sAjaxDataProp" : "aaData",
        "aoColumnDefs": [    //列定义配置数组
            { 
                "bSortable": true, //开启或关闭某列的排序
                "aTargets": [ 0 ]    //指定一个特定的列
            }
        ],
        "aaSorting": [[0, 'asc']],    // 第1列,增序
        "aLengthMenu": [ [5, 15, 20, -1], [5, 15, 20, "All"] ], //改变每页显示条数列表的选项
        
        //配置列要显示的数据
        "aoColumns": [
            {
                "mDataProp" : "id",
                "sTitle" : "<input type='checkbox'  name='allbox' id='allbox' onclick='check();' />",
                "sDefaultContent" : "",
                "bSortable" : false,
                "sClass" : "center",
                "mRender" : function(data, display, row) {
                    return "<input type='checkbox' id='"+data+"' name='idList' value='"+data+"'/>";
                }
            },
            { 
                "sTitle" : "ID",   //显示的列名
                "mDataProp": "id",  //对应的数据中的字段名
                "sDefaultContent" : "", 
                "sClass" : "center"
            },
            { 
                "sTitle" : "Name",
                "mDataProp": "name",
                "sDefaultContent" : "", 
                "sClass" : "center"
            },
            { 
                "sTitle" : "Age",
                "mDataProp": "age",
                "sDefaultContent" : "", 
                "sClass" : "center"
            },
            { 
                "sTitle" : "Update Time",
                "mDataProp": "updateTime",
                "sDefaultContent" : "", 
                "sClass" : "center",
                "mRender" : function(data, display, row) {  //将从数据库中查到的时间戳格式化
                    return new Date(data).Format("yyyy-MM-dd hh:mm:ss");
                }
                
            },
            { 
                "sTitle" : "Operate",
                "mDataProp": '',
                "sDefaultContent" : '<i class="fa fa-plus-square"><i class="fa fa-edit"></i><i class="fa fa-trash-o"></i>', //设置该列字段的值
                "sClass" : "center"
            }
        ],
        "oLanguage": { //国际化配置  
            "sProcessing" : "正在获取数据,请稍后...",    
            "sLengthMenu" : "显示 _MENU_ 条",    
            "sZeroRecords" : "没有您要搜索的内容",    
            "sInfo" : "从 _START_ 到  _END_ 条记录 总记录数为 _TOTAL_ 条",    
            "sInfoEmpty" : "记录数为0",    
            "sInfoFiltered" : "(全部记录数 _MAX_ 条)",    
            "sInfoPostFix" : "",    
            "sSearch" : "搜索",    
            "sUrl" : "",    
            "oPaginate": {    
                "sFirst" : "第一页",    
                "sPrevious" : "上一页",    
                "sNext" : "下一页",    
                "sLast" : "最后一页"    
            }
        }
        });

    /* Add event listener for opening and closing details
     * Note that the indicator for showing which row is open is not controlled by DataTables,
     * rather it is done here
     */
//    $(document).on('click','#hidden-table-info tbody td img',function () {
//        var nTr = $(this).parents('tr')[0];
//        if ( oTable.fnIsOpen(nTr) )
//        {
//            /* This row is already open - close it */
//            this.src = "images/details_open.png";
//            oTable.fnClose( nTr );
//        }
//        else
//        {
//            /* Open this row */
//            this.src = "images/details_close.png";
//            oTable.fnOpen( nTr, fnFormatDetails(oTable, nTr), 'details' );
//        }
//    } );
} );

// 日期格式转换
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //
        "s+": this.getSeconds(), //
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}

3、后台的代码

UserController类
package com.my.springmvc.controller;

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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.my.springmvc.model.User;
import com.my.springmvc.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController
{
    @Autowired
    private UserService userService;
    
    @RequestMapping("/toUser")
    public String toUser()
    {
        return "main";
    }
    
    @RequestMapping("/getUserList")
    @ResponseBody
    public Map<String, Object> getUserList(Model model)
    {
        List<User> userlist = userService.getUserList();
        Map<String, Object> map = new HashMap<>();
        map.put("aaData", userlist);
        return map;
    }
}
UserService类:
package com.my.springmvc.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.my.springmvc.dao.UserMapper;
import com.my.springmvc.model.User;

@Service
public class UserService
{
    @Autowired
    private UserMapper userMapper;
    
    public List<User> getUserList()
    {
        return userMapper.getUserList();
    }
}
UserMapper接口:
package com.my.springmvc.dao;

import java.util.List;
import com.my.springmvc.model.User;

public interface UserMapper
{
    // 查询所有用户
    public List<User> getUserList();
}
UserMapper.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.my.springmvc.dao.UserMapper">
    
    <!--获得所有用户 -->
    <select id="getUserList" resultType="User">
        SELECT
            u.id, u.name, u.age, u.updateTime
        FROM tbl_user u
    </select>
    
</mapper>
User实体类:
package com.my.springmvc.model;

import java.util.Date;

public class User
{
    private Integer id;
    private String name;
    private Integer age;
    private Date updateTime;

    @Override
    public String toString()
    {
        return "User [id=" + id + ", name=" + name + ", age=" + age + ", updateTime=" + updateTime + "]";
    }
    // ...get/set方法省略
}

4、数据库表结构:

CREATE TABLE `tbl_user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `updateTime` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8

 

5、前台页面图:

 

 

 

 

 

 

 

 

 

posted @ 2017-03-29 00:11  风止雨歇  阅读(1391)  评论(0编辑  收藏  举报