Datatables ajax请求不使用xhr但使用本地json文件

时间:2016-07-19 01:31:25

标签: angularjs angular-datatables

我在测试期间使用静态.json文件加载表。这适用于以下控制器代码:

 function dashboardResearchPubCtrl($scope, $http, dataService, DTOptionsBuilder, DTColumnBuilder) {
    var vm = this;
    vm.dtInstance = {};
          vm.dtOptions = DTOptionsBuilder.newOptions()
    .withOption('ajax', {
        "contentType": "application/json; charset=utf-8",
        dataType: "json",
        "url": "/api/research-pub.json",
        "type": "GET",
        "data": function ( d ) {
            return JSON.stringify(d);
        }
    })
    .withOption('processing', true)
    .withOption('serverSide', true)
    .withOption('filter', false)
    .withOption('fnPreDrawCallback', function () {
        $("#overlay").show();
    })
    .withOption('fnDrawCallback', function () {
        $("#overlay").hide();
    })
    .withPaginationType('full_numbers');
vm.dtColumns = [
    DTColumnBuilder.newColumn('content_id').withTitle('Id'),
    DTColumnBuilder.newColumn('content_title').withTitle('Title')
      ];
 }

但是,如果我将网址从“url”:“/ api / research-pub.json”(本地.json文件)更改为“url”:“/ api / research-pub”(xhr端点(它呈现与文件相同的json),然后数据表加载数据,但我得到数据表警告警告消息:table_id = dataTable Datatables警告:id'content_id'请求未知参数... Chrome网络显示xhr响应数据,但数据表中没有任何内容。

是否需要添加或删除参数才能使xhr正常工作?谢谢!

这是视图代码:

<div ng-controller="dashboardResearchPubCtrl as vm">
    <table id="dataTable" datatable="" dt-instance="vm.dtInstance" dt-options="vm.dtOptions" dt-columns="vm.dtColumns" class="table table-striped table-bordered table-hover dataTable"></table>
 </div>

和json回复:

[[{"rating_cnt":140,"rating_avg":4,"content_id":"122","content_title":"Business-Driven Dealer Training","content_metadata":null,"access_level":"Member","industry":"Automotive","audience_level":"Intermediate","publish_date":"2007-01-24T00:00:00.000Z"},
    {"rating_cnt":350,"rating_avg":4,"content_id":"100","content_title":"HR Training & Assessment","content_metadata":null,"access_level":"Member","industry":"Aerospace","audience_level":"Beginner","publish_date":"2014-11-14T00:00:00.000Z"}
]]

1 个答案:

答案 0 :(得分:1)

有一些问题:

  • data()回调应为dataSrc()
  • 您的JSON不遵循dataTables parameter paradigm
  • 为什么JSON.stringify() ..?这没有意义
  • 我认为.withOption('serverSide', true)是一个错误,因为JSON不支持它

d[0]中回复dataSrc(),因为回复位于[[{},{}..]表单上将会有效:

vm.dtOptions = DTOptionsBuilder.newOptions()
  .withOption('ajax', {
    url: "/api/research-pub.json",
    dataSrc: function ( d ) {
      return d[0]  
    }
  })
  ...

演示中的OP代码 - &gt; http://plnkr.co/edit/tHpb3wQbJtxikxnHrWre?p=preview

如果不需要serverSide: true,我建议改为使用承诺:

vm.dtOptions = DTOptionsBuilder.fromFnPromise(function() {
  var defer = $q.defer();
  $http.get('/api/research-pub.json').then(function(result) {
    defer.resolve(result.data[0]);
  });
  return defer.promise;
})
...