从JSON填充数据表(不是从Ajax)

时间:2019-03-02 07:50:17

标签: javascript json datatables

我试图在点击时填充数据表。 最初我有以下配置:

var json = [];
var shippingMethodsTable = $("#shipping-methods-table").DataTable({
    'data': json,
    "columns": [
        { "data": "ShippingMethodId" },
        { "data": "MethodName"},
        { "data": "Code"},
        { "data": "ShippingTypeName" },
        { "data": "MaxWeight" }
    ]
});

单击按钮后,我得到数组的json对象:

json = ko.toJSON(data.shippingMethods); // I am using knockout.js to populate it

结果:

"[{"ShippingMethodId":2,"MethodName":"Priority Mail","Code":null,"ShippingTypeName":"Parcel","MaxWeight":"70 lbs"},{"ShippingMethodId":4,"MethodName":"Priority Mail Express","Code":null,"ShippingTypeName":"Parcel","MaxWeight":"70 lbs"},{"ShippingMethodId":5,"MethodName":"First-Class Mail","Code":null,"ShippingTypeName":"Parcel","MaxWeight":"13 oz"},{"ShippingMethodId":6,"MethodName":"USPS Retail Ground","Code":null,"ShippingTypeName":"Parcel","MaxWeight":"70 lbs"},{"ShippingMethodId":8,"MethodName":"Media Mail","Code":null,"ShippingTypeName":"Parcel","MaxWeight":"70 lbs"}]"

然后我正在尝试更新数据表

shippingMethodsTable.clear();
shippingMethodsTable.rows.add('{"data":' + json + '}');
shippingMethodsTable.draw();

但出现错误:Requested unknown parameter 'ShippingMethodId' for row 0, column 0

1 个答案:

答案 0 :(得分:1)

方法rows.add()需要对象而不是对象的数组。 所以,尝试

shippingMethodsTable.clear();
shippingMethodsTable.rows.add(json);
shippingMethodsTable.draw();

相反。