DataTable 自定义返回类型
2016-02-24 10:23
330 查看
DataTable默认类型
当设置DataTables的处理方式为服务器端处理(server-side processing)时,对于服务器返回的JSON格式,DataTables期望的类型(http://datatables.net/manual/server-side#Returned-data)为{ "draw": 1, "recordsTotal": 57, "recordsFiltered": 57, "data": [ [ "Angelica", "Ramos", "System Architect", "London", "9th Oct 09", "$2,875" ], [ "Ashton", "Cox", "Technical Author", "San Francisco", "12th Jan 09", "$4,800" ], ... ] }
这样,返回的结果会自动填在表格中,并且会显示总的数目信息等.
自定义类型
但是,在我们的实际项目中,我们经常会封装返回的类型.例如,在前后端的分离中,常常会设计一个统一的响应结构,一般类似于:public class Response { private static final String OK = "ok"; private static final String ERROR = "error"; private Meta meta; private Object data; public Response success() { this.meta = new Meta(true, OK); return this; } public Response success(Object data) { this.meta = new Meta(true, OK); this.data = data; return this; } public Response failure() { this.meta = new Meta(false, ERROR); return this; } public Response failure(String message) { this.meta = new Meta(false, message); return this; } public Meta getMeta() { return meta; } public Object getData() { return data; } public class Meta { private boolean success; private String message; public Meta(boolean success) { this.success = success; } public Meta(boolean success, String message) { this.success = success; this.message = message; } public boolean isSuccess() { return success; } public String getMessage() { return message; } } }
因此,当获取到数据后,我们通常将数据设置到Response的data属性中.这样的返回格式为:
{
"meta":{"success":true, "message":"OK"},
"data":
{ "draw": 1, "recordsTotal": 57, "recordsFiltered": 57, "data": [ [ "Angelica", "Ramos", "System Architect", "London", "9th Oct 09", "$2,875" ], [ "Ashton", "Cox", "Technical Author", "San Francisco", "12th Jan 09", "$4,800" ], ... ] }
}
问题
依据DataTables默认支持的JSON类型,发现我们只需要获取对应JSON中的data属性即可.因此,在DataTables的ajax属性中,用dataSrc过滤返回给DataTables的数据,var $table = $('table').DataTable( { ... "processing" : true, "serverSide" : true, "ajax" : { data : function(d) { return $.extend({}, d, { 'name' : $('#inInput').val() }) }, dataSrc: function (json) { return json.data; }, url : "/path/url", type : "POST" } } );
但是,此时会发现,数据已经填到了表格中,但是没有关于分页的信息. 即返回的数据结构中recordsTotal,recordsFiltered没有起作用.
解决
其实,DataTables支持的数据结构中,属性draw,recordsTotal,recordsFiltered必须为顶级属性.而在dataSrc返回的结构中,draw,recordsTotal,recordsFiltered依然为子属性.这样,DataTables会找不到这些信息.修改dataSrc的返回结果为:dataSrc: function (json) { json.draw = json.data.draw; json.recordsTotal = json.data.recordsTotal; json.recordsFiltered = json.data.recordsFiltered; return json.data; }
相关文章推荐
- Android App AllowBackup配置带来的风险
- obsolete and/or deprecated parameter(s) specified
- 鼠标跟随提示框
- C++基础::运算符重载
- 腾讯 Android 面试题
- 如何设置一个App的缓存机制
- zookeeper 场景:配置文件同步
- 详解三种java实现多线程的方式
- 生成和识别二维码U3d
- curl交叉编译
- ADO编程笔记-记录遇到的问题
- 《时间同步介绍及实战配置——介绍定时任务及简单配置》
- 文本框输入测试用例
- MVC———用自定义扩展类实现验证
- c语言入门之项目3.7——用for循环输出一个等腰直角三角形
- Example #1 Serializing a single value with WDDX
- 23. gicqd
- Socket的使用
- Restful形式接口文档生成之Swagger与SpringMVC整合手记
- 存储过程定位问题