首页 > 解决方案 > 从 json 填充数据表(而不是从 ajax)

问题描述

我正在尝试在单击时填充数据表。最初我有这个配置:

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

标签: javascriptjsondatatables

解决方案


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

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

反而。


推荐阅读