关闭

jquery datatable服务端分页

标签: jquery分页
721人阅读 评论(0) 收藏 举报
分类:

OK,上次完成了客户端的分页,这次我们就在上一次的Demo上进行修改,来实现服务端的分页~
js代码:

<script type="text/javascript">
$(document).ready(function() {
    $('#table_id_example').DataTable({
        "bProcessing" : false, //是否显示加载
        "sAjaxSource" : '/datatableDemo/user/json', //请求资源路径
        "serverSide": true, //开启服务器处理模式
        /*
        使用ajax,在服务端处理数据
        sSource:即是"sAjaxSource"
        aoData:要传递到服务端的参数
        fnCallback:处理返回数据的回调函数
        */
        "fnServerData": function(sSource, aoData, fnCallback){
            $.ajax( {   
                'type' : 'post', 
                "url": sSource,    
                "dataType": "json",   
                "data": { "aodata" : JSON.stringify(aoData) },
                "success": function(resp) {   
                    fnCallback(resp);
                }   
            }); 
        }, 
        "columns" : [ 
              { data : "id" }, 
              { data : "name" }, 
              { data : "age" }, 
        ]
    });
})
</script>

开启服务器处理模式,这时我们对表格的每次操作,datatable都会帮我们向服务器发起请求获取数据,默认是用GET方式传递参数,所以我们下面加上了”fnServerData”,这样可以修改参数传递的方式为POST,那么到底给服务端发送的”aoData”是个什么鬼呢,别急,我们直接从Servlet取出来看看就知道了
此时我们的Servlet也要做一点修改:

public class Action extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 5957315496919679612L;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 编码设置
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 把传送过来的JSON字符串转成JSON数组
        JSONArray ja = JSONArray.fromObject(request.getParameter("aodata"));
        System.out.println(ja);

        // 从数据库获取数据
        List<User> listUser = Service.getInstance().getAll();

        // 数据封装并返回给客户端
        DataTableJSONResponse dtjs = new DataTableJSONResponse(listUser);
        JSONObject jsonObject = JSONObject.fromObject(dtjs);
        response.getWriter().print(jsonObject.toString());
    }

此时我们运行一下,OK,发现所谓的参数长这个模样

[{“name”:”sEcho”,”value”:1},
{“name”:”iColumns”,”value”:3},
{“name”:”sColumns”,”value”:”,,”},
{“name”:”iDisplayStart”,”value”:0},
{“name”:”iDisplayLength”,”value”:10},
{“name”:”mDataProp_0”,”value”:”id”},
{“name”:”sSearch_0”,”value”:”“},
{“name”:”bRegex_0”,”value”:false},
{“name”:”bSearchable_0”,”value”:true},
{“name”:”bSortable_0”,”value”:true},
{“name”:”mDataProp_1”,”value”:”name”},
{“name”:”sSearch_1”,”value”:”“},
{“name”:”bRegex_1”,”value”:false},
{“name”:”bSearchable_1”,”value”:true},
{“name”:”bSortable_1”,”value”:true},
{“name”:”mDataProp_2”,”value”:”age”},
{“name”:”sSearch_2”,”value”:”“},
{“name”:”bRegex_2”,”value”:false},
{“name”:”bSearchable_2”,”value”:true},
{“name”:”bSortable_2”,”value”:true},
{“name”:”sSearch”,”value”:”“},
{“name”:”bRegex”,”value”:false},
{“name”:”iSortCol_0”,”value”:0},
{“name”:”sSortDir_0”,”value”:”asc”},
{“name”:”iSortingCols”,”value”:1}]

是不是感觉有点晦涩难懂,于是本菜上网查了下,勉强是看懂这个鬼东西,接下来就讲解一下几个我们需要的参数:
sEcho:客户端发送请求同时发送过来的一个标识,虽然有什么卵用不知道,不过我们服务端返回的数据中必须带有这个标识,哦,官网的文档里说,服务端取出标识最好转一下转成int,防止XXS攻击(懵逼,暂且不管,我们只知道需要这个就行)
iColumns:列数
iDisplayStart:起始索引
iDisplayLength:显示的行数
{“name”:”mDataProp_0”,”value”:”id”},
{“name”:”sSearch_0”,”value”:”“},
{“name”:”bRegex_0”,”value”:false},
{“name”:”bSearchable_0”,”value”:true},
{“name”:”bSortable_0”,”value”:true}
每一列的参数设置,_0即是第一列,这个我们不管,到下面也是提取列名而已
sSearch:全局搜索字段
iSortCol_0:被排序的列
sSortDir_0:排序方式

完成了参数解读,那么接下来就要提取我们的参数啦~~开工加代码

public class Action extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 5957315496919679612L;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 编码设置
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 把传送过来的JSON字符串转成JSON数组
        JSONArray ja = JSONArray.fromObject(request.getParameter("aodata"));
        System.out.println(ja);

        // 获取需要的参数值
        String sEcho = null;
        Integer iColumns = null;
        Integer iDisplayStart = null;
        Integer iDisplayLength = null;
        List<String> mDataProp = new ArrayList<String>();   //存放列名
        String sSearch = null;
        Integer iSortCol_0 = null;
        String iSortCol = null;
        String sSortDir_0 = null;
        for (int i = 0; i < ja.size(); i++) {
            if (ja.getJSONObject(i).getString("name").equals("sEcho"))
                sEcho = ja.getJSONObject(i).getString("value");
            else if (ja.getJSONObject(i).getString("name").equals("iColumns"))
                iColumns = Integer.valueOf(ja.getJSONObject(i).getString("value"));
            else if (ja.getJSONObject(i).getString("name").equals("iDisplayStart"))
                iDisplayStart = Integer.valueOf(ja.getJSONObject(i).getString("value"));
            else if (ja.getJSONObject(i).getString("name").equals("iDisplayLength"))
                iDisplayLength = Integer.valueOf(ja.getJSONObject(i).getString("value"));
            else if (ja.getJSONObject(i).getString("name").equals("sSearch"))
                sSearch = ja.getJSONObject(i).getString("value");
            else if (ja.getJSONObject(i).getString("name").equals("iSortCol_0"))
                iSortCol_0 = Integer.valueOf(ja.getJSONObject(i).getString("value"));
            else if (ja.getJSONObject(i).getString("name").equals("sSortDir_0"))
                sSortDir_0 = ja.getJSONObject(i).getString("value");
            else if (iColumns != null) {
                for (int j = 0; j < iColumns; j++)
                    if (ja.getJSONObject(i).getString("name").equals("mDataProp_" + j))
                        mDataProp.add(ja.getJSONObject(i).getString("value"));
            }
        }
        iSortCol = mDataProp.get(iSortCol_0);
        System.out.println(sEcho);
        System.out.println(iColumns);
        System.out.println(iDisplayStart);
        System.out.println(iDisplayLength);
        System.out.println(sSearch);
        System.out.println(iSortCol);
        System.out.println(sSortDir_0);

        // 从数据库获取数据
        List<User> listUser = Service.getInstance().getAll();

        // 数据封装并返回给客户端
        DataTableJSONResponse dtjs = new DataTableJSONResponse(listUser);
        JSONObject jsonObject = JSONObject.fromObject(dtjs);
        response.getWriter().print(jsonObject.toString());
    }

好的,加工完毕,这时我们跑一跑看看是不是打出我们要的参数,这里我就不贴出来了,你们自己跑了看,好的发现拿到了我们要的参数,那么接下来可以拼接我们的sql语句了,同时我们要对我们的DataTableJSONResponse进行一下小小的修改,因为这里对于返回的数据也是有参数要求的,那我们就把需要的参数放进去,代码如下:

public class DataTableJSONResponse {
    Object sEcho;
    Object iTotalRecords;   //查询的记录数
    Object iTotalDisplayRecords;    //过滤后的记录数
    Object aaData;

    public DataTableJSONResponse() {
        super();
    }

    public DataTableJSONResponse(Object aaData) {
        super();
        this.aaData = aaData;
    }

    public DataTableJSONResponse(Object sEcho, Object iTotalRecords, Object iTotalDisplayRecords, Object aaData) {
        super();
        this.sEcho = sEcho;
        this.iTotalRecords = iTotalRecords;
        this.iTotalDisplayRecords = iTotalDisplayRecords;
        this.aaData = aaData;
    }

    public Object getAaData() {
        return aaData;
    }

    public void setAaData(Object aaData) {
        this.aaData = aaData;
    }

    public Object getsEcho() {
        return sEcho;
    }

    public void setsEcho(Object sEcho) {
        this.sEcho = sEcho;
    }

    public Object getiTotalRecords() {
        return iTotalRecords;
    }

    public void setiTotalRecords(Object iTotalRecords) {
        this.iTotalRecords = iTotalRecords;
    }

    public Object getiTotalDisplayRecords() {
        return iTotalDisplayRecords;
    }

    public void setiTotalDisplayRecords(Object iTotalDisplayRecords) {
        this.iTotalDisplayRecords = iTotalDisplayRecords;
    }
}

完整的Servlet:

public class Action extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 5957315496919679612L;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 编码设置
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 把传送过来的JSON字符串转成JSON数组
        JSONArray ja = JSONArray.fromObject(request.getParameter("aodata"));

        // 获取需要的参数值
        String sEcho = null;
        Integer iColumns = null;
        Integer iDisplayStart = null;
        Integer iDisplayLength = null;
        List<String> mDataProp = new ArrayList<String>();   //存放列名
        String sSearch = null;
        Integer iSortCol_0 = null;
        String iSortCol = null;
        String sSortDir_0 = null;
        for (int i = 0; i < ja.size(); i++) {
            if (ja.getJSONObject(i).getString("name").equals("sEcho"))
                sEcho = ja.getJSONObject(i).getString("value");
            else if (ja.getJSONObject(i).getString("name").equals("iColumns"))
                iColumns = Integer.valueOf(ja.getJSONObject(i).getString("value"));
            else if (ja.getJSONObject(i).getString("name").equals("iDisplayStart"))
                iDisplayStart = Integer.valueOf(ja.getJSONObject(i).getString("value"));
            else if (ja.getJSONObject(i).getString("name").equals("iDisplayLength"))
                iDisplayLength = Integer.valueOf(ja.getJSONObject(i).getString("value"));
            else if (ja.getJSONObject(i).getString("name").equals("sSearch"))
                sSearch = ja.getJSONObject(i).getString("value");
            else if (ja.getJSONObject(i).getString("name").equals("iSortCol_0"))
                iSortCol_0 = Integer.valueOf(ja.getJSONObject(i).getString("value"));
            else if (ja.getJSONObject(i).getString("name").equals("sSortDir_0"))
                sSortDir_0 = ja.getJSONObject(i).getString("value");
            else if (iColumns != null) {
                for (int j = 0; j < iColumns; j++)
                    if (ja.getJSONObject(i).getString("name").equals("mDataProp_" + j))
                        mDataProp.add(ja.getJSONObject(i).getString("value"));
            }
        }
        iSortCol = mDataProp.get(iSortCol_0);

        String sql = null;
        if(sSearch.equals(""))
            sql = "select * from(select id,name,age,rownum rn from dtdemo_xxx)"
            +"where rn between " + iDisplayStart + " and " + (iDisplayStart+iDisplayLength)
            +" order by " + iSortCol + " " + sSortDir_0;
        else
            sql = "select * from(select id,name,to_char(age,999) age,rownum rn from dtdemo_xxx where id like '%"
            + sSearch +"%' or name like '%"+ sSearch +"%' or age like '%"+ sSearch +"%')"
            +"where rn between " + iDisplayStart + " and " + (iDisplayStart+iDisplayLength)
            +" order by " + iSortCol + " " + sSortDir_0;
        System.out.println(sql);

        // 从数据库获取数据
        List<User> listUser = Service.getInstance().getAll(sql);
        //获取记录数
        int size = Service.getInstance().getAll().size();

        // 数据封装并返回给客户端
        DataTableJSONResponse dtjs = new DataTableJSONResponse(sEcho,size,size,listUser);
        JSONObject jsonObject = JSONObject.fromObject(dtjs);
        response.getWriter().print(jsonObject.toString());
    }

}

至此,服务端分页完成~

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1050次
    • 积分:30
    • 等级:
    • 排名:千里之外
    • 原创:2篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档