json - 在 Tabulator 中获取对象而不是数组
问题描述
似乎 Tabulator 期望来自 JSON 提要(通过ajax URL
方法访问)的数组以 开头和结尾[]
,但有时只有一个结果 - 所以它只是以开头和结尾{}
这在抛出的错误中很明显:
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}
]
如您所见,[]
当返回多行时添加,但对于单个结果不存在
解决方案
要更改响应,请参见此处:
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;
}
}
}
推荐阅读
- c# - 绕过 .NET Core 2.1 中的默认 AuthorizeFilter
- vue.js - 使用表格格式显示多个复选框
和 在 Vuetify 中? - dart - 如何解决 Flutter 中的“断言失败:布尔表达式不得为空”异常
- java - MalformedURLException:未知协议:android
- html - 如何在 MVC 中为一个属性获取多个复选框
- java - 将 kafka 与 jpa 一起使用时的良好做法
- google-apps-script - copyTo(destination, copyPasteType, transposed) 停止执行其余函数
- schema - JSON-LD 架构不会在 SDTT 中验证
- php - 在调用其成员函数之前检查 DOMnode 是否存在
- javascript - 我想像台球母球一样进行约束