简体   繁体   English

jQuery - 动态数据表 - 数据 JSON

[英]jQuery - Dynamic DataTable - Data JSON

I want to create a DataTable with Dynamic Columns And Data.我想创建一个包含动态列和数据的数据表。
My html code:我的 html 代码:

<body>
    <table id="example" class="display">
    </table>
</body>

My data.json:我的数据.json:

{
    "Category": {
        "0": "Bags",
        "1": "Shoes",
        "2": "School",
        "3": "Video-Games",
        "4": "PC-Games"
    },
    "Price": {
        "0": 10,
        "1": 20,
        "2": 30,
        "3": 40,
        "4": 50
    }
}

In this point, i want Category and Price to be the columns.在这一点上,我希望类别和价格成为列。

My js code is:我的js代码是:

$(document).ready(function name(params) {
    $.ajax({
        url: "data.json",
        method: 'get',
        dataType: 'json',
        success: function (response) {
            var columns = Object.keys(response).map(function (key) {
                return { title: key };
            });

            $('#example').DataTable({
                data: Object.values(response),
                columns: columns
            });
        },
        error: (error) => {
            console.log(JSON.stringify(error));
        }
    });
});

I want the below result我想要以下结果
https://i.stack.imgur.com/UkHuu.png

But i recieve this:但我收到这个:
在此处输入图像描述

The documentation suggests a slightly different data and columns formats.该文档建议使用略有不同的datacolumns格式。
for each column, you have to specify the data to use and its title对于每一列,您必须指定要使用的数据及其标题
And each row has to be an object keyed by the column data it was assigned.并且每一行都必须是一个 object,由分配给它的列data作为键控。

I admit that DataTables documentation is a bit unintuitive to navigate... But it is extensively complete.我承认 DataTables 文档导航起来有点不直观……但它非常完整。

Below is the code you should have in the Ajax success callback.以下是 Ajax success回调中应包含的代码。

 const data = { "Category": { "0": "Bags", "1": "Shoes", "2": "School", "3": "Video-Games", "4": "PC-Games" }, "Price": { "0": 10, "1": 20, "2": 30, "3": 40, "4": 50 } } const columnKeys = Object.keys(data) const columns = columnKeys.map((column) => ({title: column, data: column})) const rowKeys = Object.keys(data[columnKeys[0]]) const rows = rowKeys.map((rowKey) => { const row = {} columnKeys.forEach((columnKey) => row[columnKey] = data[[columnKey]][rowKey]) return row }) //console.log(columnKeys) console.log(columns) //console.log(rowKeys) console.log(JSON.stringify(rows)) $('#example').DataTable({ data: rows, columns: columns });
 <link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script> <body> <table id="example" class="display"> </table> </body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM