【问题标题】:Get Data from JSON file into jQuery Datatables从 JSON 文件中获取数据到 jQuery 数据表中
【发布时间】:2019-09-02 13:56:15
【问题描述】:

我正在尝试从我从 Django 脚本生成的 JSON 文件中添加数据。

这是JSON文件的格式:

[
{
    "6": "yo1",
    "1": "2019-04-04",
    "4": "yo1",
    "3": "yo1",
    "2": "yo1",
    "5": "yo1"
},
{
    "6": "yo2",
    "1": "2019-04-08",
    "4": "yo2",
    "3": "yo2",
    "2": "yo2",
    "5": "yo2"
}
] 

JavaScript:

let url = `/api/?site=${filters.site_filter}&sd=${filters.sd}&ed=${filters.ed}&report_type=yo`;

 $.getJSON(url, function(data) {data.forEach(d => {
        console.log(data);
        $('#video_data').DataTable( {
            "ajax": allData
            columns: [
            { title: "1" },
            { title: "2" },
            { title: "3" },
            { title: "4" },
            { title: "5" },
            { title: "6" }
            ]
        } );
    })
})

HTML 代码:

<table border="1" id="video_data">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Site</th>
                    <th>Page Type</th>
                    <th>Device Type</th>
                    <th>Video Player Name</th>
                    <th>AB Test</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td></td>
                </tr>
            </tbody>
        </table>

这个结果只给了我一个Loading 消息,而且我每次加载页面时都会收到这个错误:DataTables warning: table id=video_data - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3

我不知道我做错了什么?

【问题讨论】:

  • allData的值是多少?
  • 去掉forEach。您正在对该循环的每次迭代初始化插件。如果您自己提出要求,也不需要“ajax”选项

标签: javascript jquery html json datatables


【解决方案1】:

我看到一些看起来有问题的地方。

.getJSON的第一个参数应该是json文件的路径。从外观上看,allData 似乎不是一条路径。

此外,您正在循环遍历 getJson 响应中的每个项目,并一次又一次地初始化您的数据表。

最后,要使用数据集初始化表,请使用属性data 而不是ajax。应该看起来像这样:

var url = 'path/to/json/file.json';
$.getJSON(url, function(data) {
  $('#video_data').DataTable({
    data: data
  });
})

【讨论】:

  • 谢谢!但现在我收到DataTables warning: table id=video_data - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4 错误
猜你喜欢
  • 2018-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多