只需要第二眼,我正在使用MVC jQuery和DataTables,我有5个文本框和一个按钮,单击后我运行一个脚本,将数据添加到对象数组中,如下所示:
var productarray = new Array();
function addproduct() {
if ($("#ReqQuant").val() == null) {
alert("Please add product quantity")
} else if ($("#productprice").val() == null) {
alert("PLease select product")
} else {
var productname = $("#productname").val();
var productprice = $("#productprice").val();
var productquantity = $("#ReqQuant").val();
var producttotalprice = $("#OrderDetailProductTotalPricetxt").val();
var producttax = $("#OrderDetailProductTaxTXT").val();
calculatesubtotal(producttotalprice);
productarray.push({
A_productname: productname,
A_productprice: productprice,
A_productquantity: productquantity,
A_producttotalprice: producttotalprice,
A_producttax: producttax
});
var arrayjson = JSON.stringify(productarray);
$('#RetailQouteTable').DataTable().ajax.reload();
}
然后我已经在HTMl部分配置了一个表,如下所示:
<table id="RetailQouteTable">
<tr>
@*
<th>Product #</th>*@
<th>Product Name</th>
<th>Required Quantity</th>
<th>Unit Price</th>
<th>Total Price</th>
<th>Tax</th>
</tr>
</table>
下一步是像这样在脚本部分配置数据表:
$('#RetailQouteTable').DataTable({
"data": "arrayjson",
"columns":
[
{"data":"A_productname", title: "Product Name"},
{"data": "A_productquantity", title: "Required Quantity"},
{"data": "A_productprice", title: "Unit Price"},
{"data": "A_producttotalprice", title: "Total Price"},
{"data": "A_producttax", title: "Tax"}
]
});
因此,当我单击添加按钮时,数据被插入到数组中,然后收到此错误:
DataTables警告:表id = RetailQouteTable-无效的JSON响应。
我也想添加“ arrayjson”的格式,看起来像这样
"[{\"A_productname\":\"2\",\"A_productprice\":\"2.50\",\"A_productquantity\":\"10\",\"A_producttotalprice\":\"25\",\"A_producttax\":\"3.25\"},{\"A_productname\":\"3\",\"A_productprice\":\"4.90\",\"A_productquantity\":\"20\",\"A_producttotalprice\":\"98\",\"A_producttax\":\"12.74\"}]"
那我想念什么?
答案 0 :(得分:0)
我认为这行:$('#RetailQouteTable')。DataTable()。ajax.reload();导致了错误。还要尝试删除“ arrayjson”的双引号。
答案 1 :(得分:0)
它有些旧,但可能会有所帮助。
上面的代码中有多个错误:
1)在处理 DataTables.js
时,始终使用<thead>
和<tbody>
标签
将 HTML 表编辑到下面:
<table id="RetailQouteTable">
<thead>
<tr>
@*
<th>Product #</th>*@
<th>Product Name</th>
<th>Required Quantity</th>
<th>Unit Price</th>
<th>Total Price</th>
<th>Tax</th>
</tr>
<thead>
<tbody>
.
.
</tbody>
</table>
2)将 DataTable 调用更改为以下内容:
$('#RetailQouteTable').DataTable({
data: arrayjson,
columns:
[
{title: "Product Name"},
{title: "Required Quantity"},
{title: "Unit Price"},
{title: "Total Price"},
{title: "Tax"}
]
});
在arrayjson
周围使用逗号,可能会将其视为字符串,这是不正确的。
为避免任何不便,请使用以下数据格式。即Array of Arrays,例如
var arrayjson = [
[ "2", "2.50", "10", "25", "3.25"],
[ "3", "4.90", "20", "98", "12.74" ]
];
Here是有效的示例。
希望这会有所帮助。