DataTables Django Rest Framework JSON

时间:2017-10-11 19:05:57

标签: json datatables django-rest-framework

我无法在Django Rest Framework中显示DataTable的json有效负载,我不知道为什么。我已经覆盖了序列化程序以更好地格式化json有效负载,但它仍然无法工作。

我可以验证JSON请求是否正在触发并获取正确的信息(可以在浏览器的控制台中看到)但是表格显示"No data to display"

这是我的json有效载荷:

{"data":[
    {"product_name":"123",
     "mdr_class":1,
     "category":1,
     "eo_role":1,
     "division":1,
     "created_by":"root"}
    {"product_name":"1234",
     "mdr_class":1,
     "category":1,
     "eo_role":1,
     "division":1,
     "created_by":"root"}
     ...
    ]}

JSON的单行:

{"data":[{"product_name":"123","mdr_class":1,"category":1,"eo_role":1,"division":1,"created_by":"root"},{"product_name":"1234","mdr_class":1,"category":1,"eo_role":1,"division":1,"created_by":"root"},{"product_name":"234234","mdr_class":1,"category":1,"eo_role":1,"division":1,"created_by":"root"},{"product_name":"432","mdr_class":1,"category":1,"eo_role":1,"division":1,"created_by":"root"},{"product_name":"432134","mdr_class":1,"category":1,"eo_role":1,"division":1,"created_by":"root"},{"product_name":"432134","mdr_class":1,"category":1,"eo_role":1,"division":1,"created_by":"root"},{"product_name":"432134","mdr_class":1,"category":1,"eo_role":1,"division":1,"created_by":"root"}]}

和我的HTML文件概述了AJAX。

<table id="example" class="display">
<thead>
    <tr>
        <th>Product Name</th>
        <th>MDR Class</th>
        <th>Category</th>
        <th>EO Role</th>
        <th>Division</th>
        <th>Created By</th>
    </tr>
<thead>
<tbody>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
    </tr>
</tbody>
<tfoot>
    <tr>
        <th>Product Name</th>
        <th>MDR Class</th>
        <th>Category</th>
        <th>EO Role</th>
        <th>Division</th>
        <th>Created By</th>
    </tr>
<tfoot>
</table>

<script>
$(document).ready(function() {
    $('#example').DataTable( {

        ajax: {
        "processing":true,
        url: 'http://localhost:8000/api/entry/?format=json',
        "dataSrc":"",
        },


        columns: [
            {"mData":"product_name"},
            {"mData":"mdr_class"},
            {"mData":"category"},
            {"mData":"eo_role"},
            {"mData":"division"},
            {"mData":"created_by"},
            ]
        } );


});

</script>

再次 - 我可以在控制台中看到json,但数据不会显示。 我是否需要修改json如何呈现给DataTable?我很困惑。

1 个答案:

答案 0 :(得分:0)

我已经弄清楚了。 脚本格式不正确。 这是工作脚本

$(document).ready(function() {
    $('#example').dataTable( {

        ajax: {
        url: 'http://localhost:8000/api/entry/?format=json',
        },


        columns: [
            {data:"product_name"},
            {data:"mdr_class"},
            {data:"category"},
            {data:"eo_role"},
            {data:"division"},
            {data:"created_by"},
            ]
        } );


});