我有一张如下所示的表格。当多个数据来时,它可以正确显示,但如果单个数据来,则数据不显示在表格中。我怀疑单个数据中没有括号..
多个数据样本:
[{"Id":1,"Name":"Tomato soup","Category":"Groceries","Price":1.39},{"Id":2,"Name":"Yo-yo","Category":"Toys","Price":3.75},{"Id":3,"Name":"Hammer","Category":"Hardware","Price":16.99}]
单个数据样本
{"Id":1,"Name":"Tomato soup","Category":"Groceries","Price":1.39}
表和脚本:
<script type="text/javascript">
$(document).ready(function () {
function ProductViewModel() {
var self = this;
self.productData = ko.observable();
self.productId = ko.observable();
self.getAllProducts = function () {
$.get('/api/products', {}, self.productData);
};
self.getProductById = function () {
$.get('/api/products/' + self.productId(), {}, self.productData);
};
}
ko.applyBindings(new ProductViewModel());
});
</script>
<input id="txtId" type="text" data-bind="value: productId" />
<button id="btnGetSpeProduct" data-bind="click: getProductById">Get Product By Id</button>
<button id="btnGetProducts" data-bind="click: getAllProducts">Get All Products</button><br />
<table data-bind="with: productData">
<thead>
<tr>
<th>
Name
</th>
<th>
Category
</th>
<th>
Price
</th>
</tr>
</thead>
<tbody data-bind="foreach: $data">
<tr>
<td data-bind="text: Name">
</td>
<td data-bind="text: Category">
</td>
<td data-bind="text: Price">
</td>
</tr>
</tbody>
</table>