【发布时间】:2018-09-08 09:38:45
【问题描述】:
我已经有这个问题几个星期了,每次我试图找到解决方案时都没有成功,所以我希望你们中的一个人能发现我的错误。我使用了数据表调试器,它没有给出任何错误。 我在具有以下结构的 Django 项目中使用数据表。包含以下代码的文件中的 Javascript:
function redraw_exceptions(week_limit) {
var table = $('#testTable').DataTable( {
"ajax": {
"method": "GET",
"url": "api/exceptions/data",
"datatype": 'json',
"data": {
"week_limit": week_limit,
"type": 1,
},
"columns": [
{ "data": "col1" },
{ "data": "col2" },
{ "data": "col3", className: "test123" },
]
},
});
}
然后是一个 html 页面,在该页面中定义了表格,并且在文档准备就绪的地方运行了 javascript 函数。
<table class="table" id="testTable">
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
</thead>
</table>
$(document).ready(function() {
redraw_exceptions(4)
})
{%
现在问题来了。每当json数据的结构如下
{"data": [["1", "9908", "171.74"], ["2", "9959", "156.83"], ["3", "457", "153.83"], ["4", "452", "147.73"], ["5", "9927", "141.90"], ["6", "9953", "139.44"], ["7", "9915", "137.75"], ["8", "9935", "135.29"], ["9", "9952", "130.97"], ["10", "9925", "128.79"], ["11", "9934", "128.34"], ["12", "309", "127.73"], ["13", "9957", "126.08"], ["14", "451", "125.56"], ["15", "9945", "125.00"], ["16", "9921", "120.31"], ["17", "9951", "118.22"], ["18", "9926", "118.09"], ["19", "9943", "117.98"], ["20", "9954", "115.22"], ["21", "9901", "115.22"], ["22", "9939", "112.33"]]}
它可以工作(因此表实际上得到了正确的数据),但我无法将类添加到表条目中,因为我认为它无法找到正确的列,因为数据不是正确的 JSON。 但是,当数据是正确的 JSON 时,表格根本不会被填充,并且我收到错误“Requested unknown parameter '0' for row 0, column 0”。数据看起来像这样:
{"data": [{"col1": "1", "col2": "9908", "col3": "171.74"}, {"col1": "2", "col2": "9959", "col3": "156.83"}, {"col1": "3", "col2": "457", "col3": "153.83"}, {"col1": "4", "col2": "452", "col3": "147.73"}, {"col1": "5", "col2": "9927", "col3": "141.90"}, {"col1": "6", "col2": "9953", "col3": "139.44"}, {"col1": "7", "col2": "9915", "col3": "137.75"}, {"col1": "8", "col2": "9935", "col3": "135.29"}, {"col1": "9", "col2": "9952", "col3": "130.97"}, {"col1": "10", "col2": "9925", "col3": "128.79"}]}
我认为这可能是因为 Ajax 请求也有数据,所以当我将列数据更改为例如“测试”并在 JSON 数据中执行此操作时,我不再收到相同的错误,但我得到了我的控制台中出现以下错误:'TypeError: undefined is not an object (evalating 'f.length')'。
如果有人知道我可以做些什么来解决这个问题,我真的很感激!
【问题讨论】:
-
你试过了吗:"columnDefs": [ { className: "test123", "targets": [ 0 ] } ] 参考:datatables.net/reference/option/columns.className
-
您的代码没有任何问题jsfiddle.net/k8pyjz5d 您只是没有正确关闭
ajax部分,因此columns意外成为ajax的一部分。 -
这确实是正确的答案。此外,我需要将所有变量转换为字符串,然后才能正确显示在我的数据表中。感谢您的帮助!
标签: javascript jquery json datatables