javascript-使用Knockout.js从Json响应创建表
作者:互联网
我正在尝试使用Json响应和Knockout.js创建表
$(document).ready(function() {
$.ajax({
method : "POST",
url : "devTestServlet",
success : function(data) {
ko.applyBindings({
rows : data
});
}
});
});
首先,在HTML中,我在标头中导入了脚本:
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.0.0.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<link rel="stylesheet" href="css/main.css" type="text/css"></link>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
然后我在体内做了以下工作:
<table >
<tr>
<th>ID</th>
<th>Name</th>
<th>Start Date</th>
<th>Finish Date</th>
<th>Position</th>
</tr>
<tbody data-bind="foreach: rows">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: name"></td>
<td data-bind="text: Start_Date"></td>
<td data-bind="text: Finish_Date"></td>
<td data-bind="text: Position"></td>
</tr>
</table>
数据格式如下:
[
{
"id": "1",
"name": "Mike",
"Start_Date": "Sun 01/06/08",
"Finish_Date": "Sun 01/06/08",
"Position": "Trainee"
},
{
"id": "2",
"name": "Jhon",
"Start_Date": "Sun 01/06/08",
"Finish_Date": "Sun 01/06/08",
"Position": "Trainee"
},
{
"id": "2",
"name": "Jhon",
"Start_Date": "Sun 01/06/08",
"Finish_Date": "Sun 01/06/08",
"Position": "Trainee"
}
]
这是我使用Knockout.js编写的第一个程序,所以可能是我缺少了一些东西.你能建议一下吗?
解决方法:
$.ajax默认情况下以字符串形式返回响应,敲除需要一个JavaScript对象.因此,您必须将dataType指定为JSON
$.ajax({
method: "POST",
url: "devTestServlet",
dataType: 'json',
success: function(data) {
ko.applyBindings({
rows : data
});
}
});
或自己做转换
$.ajax({
method: "POST",
url: "devTestServlet",
success: function(data) {
ko.applyBindings({
rows : JSON.parse(data)
});
}
});
标签:knockout-js,json,javascript,jquery 来源: https://codeday.me/bug/20191122/2057757.html