jQuery Datatable添加行

4

我在页面中有一个datatable,初始化如下:

var dataSet = [
    { "id": 1, "name": "Bennett Weimann", "email": "jtremblay@example.com" },
    { "id": 2, "name": "Bennett Weimann", "email": "buckridge.orin@example.com" }
];

$(document).ready(function () {
    $('#example').DataTable({
        data: dataSet,
        columns: [
            { data: 'id', title: 'Id' },
            { data: 'name', title: 'Name' },
            { data: 'email', title: 'Email' },
        ],
    });
});

此外,我还有一个按钮,它会发起一个Ajax POST请求,在响应中我会得到一个JSON。

[{"id":1,"name":"Bennett Weimann","email":"jtremblay@example.com"},
{"id":2,"name":"Bennett Weimann","email":"buckridge.orin@example.com"}]

如果我尝试像下面这样添加响应,就会出错。
request.done(function (response, textStatus, jqXHR) {

        table = $('#example').DataTable();
        table.clear();
        table.rows.add(response);
        table.draw();

    });

错误是“数据表警告:表格id = example - 请求未知参数'id'的行0,列0。有关此错误的更多信息,请参见http://datatables.net/tn/4"

但是如果我手动复制和粘贴响应,就没有任何问题。

request.done(function (response, textStatus, jqXHR) {

table = $('#example').DataTable();
table.clear();
table.rows.add([
    {"id":1,"name":"Bennett Weimann","email":"jtremblay@example.com"},
    {"id":2,"name":"Bennett Weimann","email":"buckridge.orin@example.com"}
]);
table.draw();

});

请帮忙分析造成这种错误的可能原因。


我不知道你是如何执行你的 request(可以展示给我们看吗?)- 但你确定 JSON 响应是一个未命名的数组 [ { ... }, { ... } ] 而不是一个对象 { "foo": [ { ... }, { ... } ] } 吗?只是想确认一下。 - andrewJames
1个回答

1

我一定是太累了......睡醒后才发现我传递了一个对象而不是一个数组。 我正在使用 PHP 作为后端,如果我创建一个像这样的数组

    $data = array([
        "id"  => 1,
        "name" => "foo",
        "email" => "bar"
    ]);

    return $data;

通过传递响应,它能够完美地工作

 request.done(function(response, textStatus, jqXHR) {

        table = $('#example').DataTable();
        table.clear();
        table.rows.add(response);
        table.draw();

    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接