我开始在
AngularJS
和
DataTables
上工作,想知道是否可以自定义DataTables期待的响应.目前对DataTables插件的期望是这样的:
{ "draw": 1,"recordsTotal": 57,"recordsFiltered": 5,"data": [...] }
在服务器端,API正在由django-tastypie
处理
服务器的响应是:
{ Meta: { limit: 20,next: null,offset: 0,prevIoUs: null,total_count: 2 },objects: [...] }
那么,有没有办法调整Datatables插件来接受/映射这个响应,否则我将不得不找到一个方法来添加预期的字段到api?
到目前为止我已经做到了:
var deptTable = angular.element('#deptManagementTable').DataTable({ processing: true,serverSide: true,pagingType: "simple_numbers",ajax: { url: "/client/api/v1/departments/",data: function(d) { d.limit = d.length; d.offset = d.start; d.dept_name__icontains = d.search.value; },dataSrc: function(json) { for (var i=0,len=json.objects.length ; i<len ; i++) { json.objects[i].DT_RowId = json.objects[i].dept_id; } return json.objects; } },aLengthMenu: [ [5,25,50,100],[5,100] ],iDisplayLength: 5,columns: [ { data: "dept_name" },{ data: "dept_created_on",render: function ( data,type,full,Meta ) { var dateCreated = new Date(data); dateCreated = dateCreated.toLocaleDateString(); return dateCreated; } } ] });
任何帮助将不胜感激.
提前致谢 :)
您可以将功能传递给DataTables
原文链接:/ajax/159818.htmlajax
option,这将使您完全控制如何在将数据传递到DataTables之前获取和映射数据.
.DataTable({ serverSide: true,ajax: function(data,callback,settings) { // make a regular ajax request using data.start and data.length $.get('/client/api/v1/departments/',{ limit: data.length,offset: data.start,dept_name__icontains: data.search.value },function(res) { // map your server's response to the DataTables format and pass it to // DataTables' callback callback({ recordsTotal: res.Meta.total_count,recordsFiltered: res.Meta.total_count,data: res.objects }); }); } });
上述解决方案已经通过jQuery DataTables 1.10.4进行了测试.
由于这个问题是用Angular标记的,所以这里是使用angular-datatables的解决方案.
<div ng-controller="testCtrl"> <table datatable dt-options="dtOptions" dt-columns="dtColumns" class="row-border hover"></table> </div>
.controller('testCtrl',function($scope,$http,DTOptionsBuilder,DTColumnBuilder) { $scope.dtOptions = DTOptionsBuilder.newOptions() .withOption('serverSide',true) .withOption('ajax',function(data,settings) { // make an ajax request using data.start and data.length $http.get('/client/api/v1/departments/',{ limit: data.length,dept_name__icontains: data.search.value }).success(function(res) { // map your server's response to the DataTables format and pass it to // DataTables' callback callback({ recordsTotal: res.Meta.total_count,data: res.objects }); }); }) .withDataProp('data'); // IMPORTANT¹ $scope.dtColumns = [ // your column definitions here ]; });
上述解决方案已经使用角度数据表0.3.0 DataTable 1.10.4进行了测试.
¹这里要注意的重要部分是角度数据表解决方案要求.withDataProp(‘data’)可以工作,而纯jQuery DataTables解决方案没有数据:’data’选项.