【问题标题】:Getting object instead of array in Tabulator在 Tabulator 中获取对象而不是数组
【发布时间】:2020-06-30 12:36:46
【问题描述】:

似乎 Tabulator 期望来自 JSON 提要(通过 ajax URL 方法访问)的数组以 [] 开头和结尾,但有时只有一个结果 - 所以它只是以 @ 开头和结尾987654323@

这在抛出的错误中很明显:

Data Loading Error - Unable to process data due to invalid data type 
Expecting: array 
Received:  object 

有没有办法解决这个问题?

对于单个结果,我的数据如下所示:

{"empId":"123456","firstName":"bini the third","lastName":"rouge","birthDate":"1986-05-04T00:00:00.000+0000","gender":"M","mother":false}

对于多行结果,就像这样:

[
 {"empId":"123456","firstName":"bini the third","lastName":"rouge","birthDate":"1986-05-04T00:00:00.000+0000","gender":"M","mother":false},
 {"empId":"1111","firstName":"bini the third","lastName":"rouge","birthDate":"1976-05-04T00:00:00.000+0000","gender":"M","mother":false}
]

如您所见,[] 在返回多行时添加,但对于单个结果不存在

【问题讨论】:

  • 您是发送 JSON 的 API 开发者吗?如果是这样,只需对其进行编程,以便 API 始终返回一个数组。一个端点上的模棱两可的返回类型通常很糟糕。
  • 会试试的,谢谢。但仍然想知道 Tabulator 是否可以在没有 [] 的情况下使用这种格式。

标签: json tabulator


【解决方案1】:

要更改响应,请参见此处:

http://tabulator.info/docs/4.7/data#ajax

Ajax 响应格式

Altering The Response

Tabulator expects the response to an ajax request to be a JSON encoded string representing an array of data objects. If you need to pass other data back in your request as well, you can use the ajaxResponse callback to process the returned data before it is passed to the table. The return value of this callback should be an array of row data objects.

var table = new Tabulator("#example-table", {
    ajaxResponse:function(url, params, response){
        //url - the URL of the request
        //params - the parameters passed with the request
        //response - the JSON object returned in the body of the response.

        return response.tableData; //return the tableData property of a response json object
    },
});

您可以将您的单个对象包含在一个数组中以返回到 Tabulator。

一个简单的例子:

ajaxResponse: function(url, params, response){
        if( Object.prototype.toString.call(response) === '[object Array]' ) {
            return response;
            
       }else{if( Object.prototype.toString.call(response) === '[object Object]' ) {
           var rsArray = [];
           rsArray.push(response)
           return rsArray;
    }


       }
    }

【讨论】:

  • 谢谢。你能为此设置一个非常快速的演示吗?泰!
  • 我添加了一个例子。不幸的是,我还没有弄清楚如何让 jsFiddle 处理 AJAX 请求/响应,所以我没有一个活生生的例子。
  • 这是一个简单的阿德里安,如果您将另一个文件添加到包含 JSON 格式数据的 test.json 之类的小提琴中,则使用 ./test.json 作为 ajaxUrl 值
  • 嗯。我似乎无法弄清楚如何将文件添加到 jsFiddle。有什么例子可以指点我吗?
猜你喜欢
  • 1970-01-01
  • 2017-12-16
  • 1970-01-01
  • 2020-03-28
  • 2018-04-19
  • 2020-03-01
  • 1970-01-01
  • 2021-02-11
相关资源
最近更新 更多