如何使用本地 JSON 对象作为 jQuery DataTables 的数据源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9669812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:08:12  来源:igfitidea点击:

How can I use a local JSON object as a data source for jQuery DataTables

jqueryjsondatatables

提问by codecowboy

I have a local JSON object formatted like this:

我有一个格式如下的本地 JSON 对象:

[{
    "id": "58",
    "country_code": "UK",
    "title": "Legal Director",
    "pubdate": "2012-03-08 00:00:00",
    "url": "http://..."
},{
    "id": "59",
    "country_code": "UK",
    "title": "Solutions Architect,",
    "pubdate": "2012-02-23 00:00:00",
    "url": "http://..."
},{
    // ....more of the same......
}]

I would like to set this as the data source for a jQuery datatableand have tried this:

我想设置此作为一个jQuery的数据源的数据表,并尝试这样的:

testdata = '{{ jobsJSON | raw }}'; //twig template tag
console.log(testdata);
$('#test').dataTable({
    "aoData": testdata,
    "aoColumns": [
        { "mDataProp": "id" },
        { "mDataProp": "country_code" },
        { "mDataProp": "title" },
        { "mDataProp": "pubdate" },
        { "mDataProp": "url" }
    ]
});

The DataTables plugin loads and attempts to draw the table but gives the error 'No data available in table'

DataTables 插件加载并尝试绘制表格,但给出错误“表格​​中无可用数据”

I am not making an AJAX call and just want to access the JSON object from a local JS variable.

我不是在进行 AJAX 调用,只是想从本地 JS 变量访问 JSON 对象。

回答by Rory McCrossan

The property to supply your own data is aaDataNOT aoData:

提供您自己的数据的属性aaData不是aoData

testdata = [{"id":"58",...}]; // local object

$('#test').dataTable({
    "aaData": testdata,
    "aoColumns": [
        { "mDataProp": "id" },
        { "mDataProp": "country_code" },
        { "mDataProp": "title" },
        { "mDataProp": "pubdate" },
        { "mDataProp": "url" }
    ]
});

Working fiddle

工作小提琴

回答by Kenji

I encoutered the same problem, solution is like this: Place $('#list_table').dataTablecode in setTimeoutfunction to postpone dataTable application for 5 seconds:

我遇到了同样的问题,解决方案是这样的:$('#list_table').dataTablesetTimeout函数中放置代码以推迟数据表应用程序5秒:

setTimeout("$('#list_table').dataTable ...." , 5000);

I noticed that apply dataTable plugin in firebug after the table is loaded, it doesn't show error as "No data available in table".

我注意到在加载表后在萤火虫中应用 dataTable 插件,它不会显示错误为“表中无可用数据”。