我正在尝试从 ajax 服务器读取绑定 observableArray,但无法将其绑定到 html。json 数据正在返回,但不确定如何解析或绑定。我是新来的淘汰赛。
代码:
<html>
<head>
<title></title>
<script type='text/javascript' src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>
<script type='text/javascript' src="http://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.3.5/knockout.mapping.js"></script>
<script type='text/javascript' src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.js"></script>
<script>
function SurnameViewModel() {
var self = this;
self.Surnames = ko.observableArray();
$.ajax({
crossDomain: true,
type: 'POST',
url: "http://localhost/GetSurnames/Name/CID",
dataType: 'json',
data: { "Name": "d", "CID": "17" }, // <==this is just a sample data
processdata: true,
success: function (result) {
self.Surnames= ko.mapping.fromJS(result.data);
alert(self.Surnames()); // <== able to see the json data
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Failure!");
alert(xhr.status);
alert(thrownError);
}
});
}
// Activates knockout.js
$(document).ready(function() {
ko.applyBindings(new SurnameViewModel())
});
</script>
</head>
<body>
<h2>Surnames</h2>
<table>
<thead><tr>
<th>ID</th><th>Surname</th>
</tr></thead>
<tbody data-bind="foreach: Surnames">
<tr>
<td data-bind="text: Surnames().id"></td>
<td data-bind="text: Surnames().homename"></td>
</tr>
</tbody>
</table>
</body>
</html>
从警报返回的 Json 数据
data: "[{"id":3,"homename":"DCosta"}]"
这里做错了什么?
编辑:工作代码
这对我有用。
我改变这个
ko.mapping.fromJS(result.data, {}, self.Surnames);
至
ko.mapping.fromJSON(result.data, {}, self.Surnames);
并在此的 html 中
<tr>
<td data-bind="text: Surnames().id"></td>
<td data-bind="text: Surnames().homename"></td>
</tr>
对此
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: homename"></td>
</tr>