数据表 - 将JSON数据加载到表中

时间:2018-01-17 17:56:27

标签: jquery json api datatables

我正在使用数据表,我有数据来自API,我如何填充我的表?响应采用JSON密钥对格式

{
    "site": "SITE A",
    "sent": "141558",
    "open": "470",
    "click": "0",
    "delivered": "0",
},
{
        "site": "SITE B",
        "sent": "141558",
        "open": "470",
        "click": "0",
        "delivered": "0",
    },

HTML

<table id="example" class="table datatable-basic table-bordered table-striped table-hover" width="100%" cellspacing="0" style="text-align:center;">
  <thead style="text-align:center;background-color:#BE1E2D; color:white">
                       <tr>
                                <th>Site Visited</th>
                                <th>Sent</th>
                                <th>Open</th>
                                <th>Clicked</th>
                                <th>Delivered</th>
                            </tr>
                            </thead>

                        </table>

的Javascript

$('#getData').on('click', function () {

        $('#example').DataTable( {
            "ajax": 'http://localhost/API/index.php'
        } );
    });

2 个答案:

答案 0 :(得分:0)

将您的JavaScript更改为:

$('#example').DataTable( {
        "ajax": "http://localhost/API/index.php",
        "columns": [
            { "data": "site" },
            { "data": "sent" },
            { "data": "open" },
            { "data": "click" },
            { "data": "delivered" }           
        ]
    } );

答案 1 :(得分:0)

如果你从api获得一个对象数组,你应该使用columns属性,如果它也是你应该指定的帖子请求:

$(document).ready(function() {
    $('#example').DataTable( {
        "ajax": {
             "url": "http://localhost/API/index.php",
             "type": "POST"
         },
        "columns": [
            { "data": "site" },
            { "data": "sent" },
            { "data": "open" },
            { "data": "click" },
            { "data": "delivered" }
        ]
    } );
} );