首页 > 解决方案 > Datatable.js 从 JSON 数据动态设置列标题

问题描述

我正在使用 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 来列出和放置它们,也不知道究竟是如何......

标签: jsondatatablestitleput

解决方案


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

// 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"
            }
        });
    }
});

推荐阅读