我正在尝试使用 Knockout 将从 Grails 控制器返回的 JSON 数据数据绑定到表。我相信返回的 JSON 很好:
result
[
Object
class: "project.Person"
firstName: "Bill"
id: 2
lastName: "Fake"
__proto__: Object
,
Object
class: "project.Person"
firstName: "Dale"
id: 3
lastName: "Fake"
__proto__: Object
,
Object
class: "project.Person"
firstName: "Linda"
id: 4
lastName: "Fake"
__proto__: Object
]
这是我的javascript:
var Directory = {
list: ko.observableArray([])
};
var Person = function(id, first, last) {
this.id = ko.observable(id);
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
};
var loadPeople = function() {
$.ajax({
url: "${createLink(action: "getPeople")}",
type: "post",
contentType: "application/json",
success: function(result) {
for(p in result) {
Directory.list.push(new Person(p.id,p.firstName,p.lastName));
}
ko.applyBindings(Directory);
}
});
};
loadPeople();
最后,我的标记:
<table>
<thead>
<tr><th>Id</th><th>First name</th><th>Last name</th></tr>
</thead>
<tbody data-bind="foreach: list">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: firstName"></td>
<td data-bind="text: lastName"></td>
</tr>
</tbody>
</table>
我查看了类似的问题并尝试list.Person
将Person
可观察数组传递给绑定而不是Directory
. 当我调试时,包含一个类型Directory.list()
大小的数组,所以它看起来是正确的。3
Person
错误:
未捕获的错误:无法解析绑定属性。消息:ReferenceError:id 未定义;属性值:文本:id
任何帮助表示赞赏。