jQuery数据表在ajax中使用dataSrc并且列不起作用

时间:2017-06-17 07:27:53

标签: jquery ajax

$('#treatmentTable').DataTable({
    "bFilter": false,
    "ordering": false,
    "columnDefs": [
        { "orderable": false, "targets": 2 }
    ],
    "bLengthChange": false,
    "bInfo": false,
    "bAutoWidth": false,
    "processing": true,
    "serverSide": true,
    "ajax": { 
        "url": $(".baseurl").val()+'GetAPI.php?func=getTreatment',
        "type": "post",
        "dataSrc": function ( json ) {
           console.log(json.data);
        }  
    },
    "columns": [
        { "data": "treatment_name", "width":"40%" },
        {
            "data": null,
            "bSortable": false,
            "mRender": function (o) { return '€ '+o.treatment_price.replace(".",","); }
        },
        { "data": "treatment_duration"}
    ]
});

我正在使用jquery数据表,而当时我使用的是列和ajax dataSrc,错误显示为Uncaught TypeError: Cannot read property 'length' of undefined

从ajax返回: {"draw":"1","recordsTotal":10,"recordsFiltered":8,"data":[{"treatment_id":"27","treatment_name":"ttt","treatment_price":"22.10","treatment_duration":"15","barberid":"94"}}]}

寻求帮助。

1 个答案:

答案 0 :(得分:1)

在第二列中使用渲染选项渲染它,在渲染功能中只传递1个参数,表示数据字段而不是整行,所以要获得完整的行,需要将3个参数传递给函数 点击这里https://datatables.net/reference/option/columns.render

用这个改变它

"mRender": function ( data, type, o) { return '€ '+o.treatment_price.replace(".",","); }

修改

您会看到处理标签,因为您没有从dataSrc函数返回数据

"ajax": {
    "url": 'upload.php',
    "type": "post",
    "dataSrc": function (json) {
        console.log(json.data);
        return json.data; // you need to return data array here
    }
}

已满

    $('#treatmentTable').DataTable({
        "bFilter": false,
        "ordering": false,
        "columnDefs": [
            {"orderable": false, "targets": 2}
        ],
        "bLengthChange": false,
        "bInfo": false,
        "bAutoWidth": false,
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": 'upload.php',
            "type": "post",
            "dataSrc": function (json) {
                console.log(json.data);
                return json.data;
            }
        },
        "columns": [
            {"data": "treatment_name", "width": "40%"},
            {
                "data": null,
                "bSortable": false,
                "mRender": function (d,t,o) {
                    return '€ ' + o.treatment_price.replace(".", ",");
                }
            },
            {"data": "treatment_duration"}
        ]
    });
});