我有一张表“应该”与json的结果绑定,但它不起作用,可能是错误?
<table>
<thead>
<tr>
<th>
Id
</th>
<th>
Number
</th>
<th>
Name
</th>
<th>
Password
</th>
<th>
Role
</th>
</tr>
</thead>
<tbody data-bind="foreach: model.Employees">
<tr>
<td>
<span data-bind="text: EmployeeId"></span>
</td>
<td>
<span data-bind="text: EmployeeNumber"></span>
</td>
<td>
<span data-bind="text: EmployeeName"></span>
</td>
<td>
<span data-bind="text: EmployeePassword"></span>
</td>
<td>
<span data-bind="text: EmployeeRole"></span>
</td>
</tr>
</tbody>
我的淘汰剧本是这样的:
<script type="text/javascript">
$(document).ready(function () {
var viewModel = {};
var data = $.getJSON("Employees.json", function (data) {
viewModel= ko.mapping.fromJSON(data);
ko.applyBindings(viewModel);
}
);
});
</script>
这是我的样本返回的json数据:
{"Employees":[{"EmployeeId":1,"EmployeeName":X","EmployeeNumber":"1","EmployeePassword":"x","EmployeeRole":"User"},{"EmployeeId":10,"EmployeeName":"S","EmployeeNumber":"21","EmployeePassword":"s","EmployeeRole":"Admin"}]}
答案 0 :(得分:4)
如果你打开浏览器的错误控制台我打赌你会看到这样的事情:
<{1}}未定义未捕获错误:无法解析绑定。消息:ReferenceError: 员工没有定义;绑定价值:foreach:员工
Employees
。但是,它是在viewModel
上定义的。如果您要么: - / p>
viewModel.model
data-bind
上的foreach代替:
model.Employees
将AJAX请求的结果直接分配给<tbody data-bind="foreach: model.Employees">
而不是viewModel
:
viewModel.model
另外作为旁注,不需要分配viewModel = ko.mapping.fromJSON(data);
,因为回复函数处理了响应:
var data = $.getJSON(...)