【问题标题】:Datatable.js set column title dynamically from JSON dataDatatable.js 从 JSON 数据动态设置列标题
【发布时间】:2019-10-03 15:59:41
【问题描述】:

我正在使用 Datatabls 通过 ajax 显示表格数据。但有时列名不同。所以我用 json 数据从服务器获取它们的数组列表。现在使用空的thead并希望将实际的列名放在那里。

我的 JS:

$('#DTable').DataTable({
    "processing": true,
    "serverSide": true,
    "ajax": {
        "url": "data.php",
        "type": "POST",
        "dataType": "json",
        "dataSrc": "data"
    }
});

我的 JSON:

{
"col": [
    "A",
    "B",
    "C",
    "D",
    "E"
],
"data": [
    [
        "Umn(i4(5P~",
        "wA~W70Vtmj",
        "^taMfGgmKC",
        "klPx6XrZR*",
        "H6ooRlotEB"
    ],
    [
        "DrUE)Z234C",
        "udN2BJOSpn",
        "GWjU3~*hbr",
        "IFIk1t1!m(",
        "kH*Yypo5)E"
    ],
    [
              .........
    ]
]}

假设我需要使用:

        "dataFilter": function(res) {
            res.col.....
        }

"columnDefs": [
      { "title": "My custom title", "targets": 0 }
]

但我的数据奇怪不是 json 数据类型,我不能使用 res.col 列出和放置它们,也不知道究竟是如何......

【问题讨论】:

    标签: json datatables title put


    【解决方案1】:

    好的。我找到了解决方案。也许不是最好的,但它的工作原理。

    // First call standard ajax request for getting column names
    $.ajax({
        url: "data.php",
        type: "POST",
        dataType: "json",
        success: function(res) {
    
            //put column names into thead
            $('#DTable thead tr').empty();
            var cols=res.col;
            for (var i=0; i<cols.length; i++) {
                $('#DTable thead tr').append('<th>'+cols[i]+'</th>');
            }
    
            // initialise Datatable
            $('#DTable').DataTable({
                processing: true,
                serverSide: true,
                deferRender: true,
                ajax: {
                    url: "data.php",
                    type: "POST",
                    dataType: "json",
                    dataSrc: "data"
                }
            });
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-01
      • 1970-01-01
      • 2013-06-29
      • 2013-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多