首页 > 解决方案 > 在 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}
]

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

标签: jsontabulator

解决方案


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

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;
    }


       }
    }

推荐阅读