Datatable.js根据JSON数据动态设置列标题

Datatable.js根据JSON数据动态设置列标题,json,datatables,title,put,Json,Datatables,Title,Put,我使用数据表通过ajax显示表数据。但有时列名是不同的。因此,我使用json数据从服务器阵列列表中获取它们。现在使用空thead并希望将实际列名放在那里 我的JS: $('#DTable').DataTable({ "processing": true, "serverSide": true, "ajax": { "url": "data.php", "type": "POST", "dataType": "json",

我使用数据表通过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.....
        }


但是我的数据不是json数据类型,我不能使用res.col来列出和放置它们,也不知道确切的方式……

OK。我找到了解决办法。也许不是最好的,但它起作用了

// 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"
            }
        });
    }
});
//首先调用获取列名的标准ajax请求
$.ajax({
url:“data.php”,
类型:“POST”,
数据类型:“json”,
成功:功能(res){
//将列名放入AD
$('#DTable thead tr').empty();
var cols=res.col;
对于(var i=0;i
// 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"
            }
        });
    }
});