如何在数据表中显示来自get请求的数据?

时间:2017-07-03 07:48:42

标签: javascript angularjs json rest datatables

我一直试图显示我的休息应用程序的json响应,这是使用tomcat服务器的休息应用程序,我在前端使用角度,这是我的控制器

(function(){
    'use strict';
    angular.module('app')
        .controller('wfCtrl', wfCtrl);

    function wfCtrl($scope, $location, $http) {

           var table=$('#example1').DataTable(
    {
              "bServerSide": true,
                "fnServerData": function (sSource, aoData, fnCallback) {
                    var myData = JSON.stringify(aoData);
                    $.ajax({
                        "dataType": 'json',
                        "contentType" : "application/json;charset=utf-8",
                        "type": "GET",
                        "url": "http://localhost:8080/Spring4/data/lworkflows",
                        "data": null,
                        "success": fnCallback,
                        "error": function () {
                            console.log('have some problem');
                        }
                    });
                },      
"aoColumns": [
  { "mData": null },  // for User Detail
  { "mData": "code" },
  { "mData": "label" },
  { "mData": null },
  { "mData": null },
  { "mData": null },
  { "mData": null },
]
,
"order": [[ 1, "desc" ]]});

})();

请求网址" http://localhost:8080/Spring4/data/lworkflows"返回像这样的json数据

{"WFLIGHT":{"code":"WFLIGHT","label":"Submit the deal"},"WFCOM":{"code":"WFCOM","label":"COM"},"WFPOCTBR":{"code":"WFPOCTBR","label":"Workflow Retail POC VW"},"WFRISK":{"code":"WFRISK","label":"RISQUES"},"WFDECF":{"code":"WFDECF","label":"DECIDEUR"},"WFETUDE":{"code":"WFETUDE","label":"ETUDE"},"WFADV":{"code":"WFADV","label":"ADV"},"TEST1":{"code":"TEST1","label":"Workflow Retail POC VW"},"WFCOM2":{"code":"WFCOM2","label":"ASSCOM"}}

我得到的错误是

  

未捕获的TypeError:无法读取属性'长度'未定义的

因为我的数据表无法读取从请求发送的数据

我该如何解决?

1 个答案:

答案 0 :(得分:0)

将响应转换为数组后

解决了

var output = wfs.map(function(obj) {
  return Object.keys(obj).sort().map(function(key) { 
    return obj[key];
  });

这里是完整的工作代码

 function wfCtrl($scope, $location, $http) {


        $http({
          method: 'GET',
          url: 'http://10.10.216.201:8080/Spring4/data/lworkflows'
        }).then(function successCallback(response) {
          var wfs = response.data;

         var output = wfs.map(function(obj) {
  return Object.keys(obj).sort().map(function(key) { 
    return obj[key];
  });

});
 console.log(output);
           var table=$('#example1').DataTable(
    {
        "data":output,
  "columns": [
   { "className":      'details-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": '' },
    null,
    null,
    null,
    null,
    null,
     { "orderable": false }
  ]
,
"order": [[ 1, "desc" ]]});

        }, function errorCallback(response) {
          console.log("error");
        });

}