没有数组的JQuery数据表 [英] JQuery Datatables without Array

查看:83
本文介绍了没有数组的JQuery数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在填充表时遇到问题,无法访问具有JSON这样的文本文件:

I'm having trouble populating a table, accessing a text file that has JSON like this:

{
    "1000": {
        "country": "US",
        "eventid": 1000,
        "venue": "San Francisco, USA"
    },
    "2000": {
        "country": "DE",
        "eventid": 2000,
        "venue": "Munich, Germany"
    },
    "3000": {
        "country": "GB",
        "eventid": 3000,
        "venue": "UK (Market House)"
    }
}

我已按照datatables.net上的示例尝试将其加载到HTML中

I have followed the examples on datatables.net and tried loading it on to my HTML

<HTML>
    <head>
        <title>Hello World</title>
        <link rel="stylesheet" type="text/css" href="bootstrap.min.css"/>
        <link rel="stylesheet" type="text/css" href="dataTables.bootstrap.css"/>
        <script type="text/javascript" src="jquery-1.11.1.min.js"></script>
        <script type="text/javascript" src="jquery.dataTables.min.js"></script>
        <script type="text/javascript" src="datatable.js"></script>
        <script type="text/javascript" src="dataTables.bootstrap.js"></script>
    </head>
    <body>
        <table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
            <thead>
                <tr>
                    <th>Country</th>
                    <th>Event</th>
                    <th>Venue</th>
                </tr>
            </thead>
        </table>
    </body>
</html>

datatable.js就这么简单

And the datatable.js is as simple as this

$(document).ready(function() {
    $('#example').dataTable( {
        "processing": true,
        "ajax": 'sample.txt',
        "columns": [
            { "country" },
            { "eventid" },
            { "venue" }
        ]
    } );
} );

有人可以帮我弄清楚我的代码出了什么问题吗?

Can someone help me figure out where I have gone wrong with the code ?

推荐答案

我设法通过添加一个自定义函数作为dataSrc属性的一部分来解决了该问题(感谢Lin Jongyu Lin)。这是对我的Javascript的更改

I managed to fix the issue by adding a custom function as part of dataSrc attribute (Thanks Jongyu Lin). Here is the change to my Javascript

$(document).ready(function () {
    $('#example').dataTable({
        "processing": true,
        "ajax": {
            "url": 'json.txt',
            "dataSrc": function (json) {
                var arr = Object.keys(json).map(function(k) { return json[k] });
                return arr;
            }
        },
        "columnDefs": [
            {
                "targets": [2],
                "visible": true,
                "searchable": true
            }
        ],
        "columns": [
            {
                "data": "eventid"
            },
            {
                "data": "country"
            },
            {
                "data": "venue"
            }
        ]
    });
});

这篇关于没有数组的JQuery数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆