【发布时间】:2020-10-02 08:02:49
【问题描述】:
我正在尝试使用此 HTML 显示来自 Ajax 源的数据:
<table class="table-striped data-table" data-src="https://my.site/json-url" data-columns='["id","sku","name","base_stock","stock","sales"]'>
<thead>
<tr>
<th>ID</th>
<th>SKU</th>
<th>Name</th>
<th>Initial Stock</th>
<th>Current Stock</th>
<th>Sales</th>
</tr>
</thead>
</table>
还有这个 JS:
$('.data-table').each(function(){
var src = $(this).data('src');
var cols = $(this).data('columns').map(x => {return {data: x};});
$(this).DataTable({
"responsive": true,
"ajax": src,
"columns": cols
});
});
其中,https://my.site/json-url 通常会回复:
{
"status": "success",
"data": [
{
"id": 1515,
"sku": "",
"name": "Test Simple",
"base_stock": 10,
"stock": 10,
"sales": 0
},
{
"id": 1512,
"sku": "BWTEST",
"name": "Test Variable - Black / White",
"base_stock": 9,
"stock": 9,
"sales": 0
},
{
"id": 1513,
"sku": "CLRTEST",
"name": "Test Variable - Multi-Color",
"base_stock": 4,
"stock": 4,
"sales": 0
}
]
}
但是,我收到错误消息:Uncaught TypeError: cannot use 'in' operator to search for "length" in "id" jquery.min.js:2:1065。有人可以帮忙吗?
注意:我可以看到实际上没有向 https://my.site/json-url 发出 ajax 请求,因此错误似乎在 ajax 调用之前就已经发生了。
【问题讨论】:
-
如果您对结果结构感到好奇,控制台中的选项数组如下所示:
{ "responsive": true, "ajax": "https://my.site/json-url", "columns": [ "id", "sku", "name", "base_stock", "stock", "sales" ], "src": "https://my.site/json-url", "aoColumns": [ "id", "sku", "name", "base_stock", "stock", "sales" ] }
标签: jquery ajax datatables