嗨,我正在使用带有 Knockout 的 web api 开发简单的 web。我想显示来自 Json 结构的数据列表。
function OrganisationViewModel() {
var self = this;
self.Organisations = ko.observableArray();
var baseUri = '@ViewBag.ApiUrl';
$.getJSON(baseUri, self.Organisations);
}
$(document).ready(function () {
ko.applyBindings(new OrganisationViewModel());
})
上面的代码是获取 JSON 并将其设置为 Observable 数组。
<div>
<ul id="update-Org" data-bind="foreach: Organisations">
<li>
<div>
<span data-bind:"text: $data.Name"></span>
</div>
<div>
<span data-bind:"value: $data.PhoneNumber"></span>
</div>
</li>
</ul>
</div>
上面是用于打印 JSON 数据的 HTML。输出只返回 4 个点。这意味着它知道我在数组中有 4 个项目。我很确定这与空 JSON 数据无关,因为我得到了 JSON 数据。
0: {$id:1, Contacts:[{$id:2, Organisation:{$ref:1}, Id:1, ContactName:bg1, OrganisationId:1},…],…}
$id: "1"
Contacts: [{$id:2, Organisation:{$ref:1}, Id:1, ContactName:bg1, OrganisationId:1},…]
0: {$id:2, Organisation:{$ref:1}, Id:1, ContactName:bg1, OrganisationId:1}
1: {$id:3, Organisation:{$ref:1}, Id:2, ContactName:bg2, OrganisationId:1}
2: {$id:4, Organisation:{$ref:1}, Id:3, ContactName:bg3, OrganisationId:1}
Devices: []
Id: 1
Licenses: []
Name: "Aug1"
PhoneNumber: "021"
1: {$id:5, Contacts:[], Licenses:[], Devices:[], Id:2, Name:Aug2, PhoneNumber:02111}
$id: "5"
Contacts: []
Devices: []
Id: 2
Licenses: []
Name: "Aug2"
PhoneNumber: "02111"
2: {$id:6, Contacts:[], Licenses:[], Devices:[], Id:3, Name:Aug3, PhoneNumber:0211333}
$id: "6"
Contacts: []
Devices: []
Id: 3
Licenses: []
Name: "Aug3"
PhoneNumber: "0211333"
.....