我正在尝试将JSON字符串转换为knockout.js可观察数组。
这是我的js代码:
$(document).ready(function(e){
var model = function(dat){
this.tabledata = ko.observableArray(dat);
};
$.ajax({
url: 'http://localhost:1141/rest_service/show_data',
type: 'GET',
success: function(msg){
// var dat = JSON.parse(msg);
alert(msg);
ko.applyBindings(new model(msg));
},
error: function(msg){
alert(JSON.stringify(msg));
},
});
});这是我的html:
<table id = "example" >
<thead>
<tr>
<th>Employee ID</th>
<th>Employee Name</th>
<th>Employee Status</th>
<th>Date of birth</th>
<th>Age</th>
</tr>
</thead>
<tbody data-bind='foreach: tabledata'>
<tr>
<td data-bind='text: $parent.empId'/></td>
<td data-bind='text: $parent.empStatus'/></td>
<td data-bind='text:$parent.dob'/></td>
<td data-bind='text: $parent.empName'/></td>
<td data-bind='text: $parent.age'/></td>
</tr>
</tbody>
</table>因此,在ajax调用之后,我将从服务器获得一个JSON字符串作为响应,并希望将此数据绑定到html表。
我尝试使用ko.mapping.fromJs()将传入的JSON转换为可观察的数组,但收到了以下错误:
Error: The argument passed when initializing an observable array must be an array, or null, or undefined.JSON响应如下:
[
{"empId":100,"empName":"TA","empStatus":"yes","dob":"2000-12-12","age":15},
{"empId":101,"empName":"TA","empStatus":"yes","dob":"2000-12-12","age":15},
{"empId":102,"empName":"TATA","empStatus":"yes","dob":"1997-12-12","age":18},
{"empId":103,"empName":"kljh","empStatus":"yes","dob":"2000-12-12","age":15},
{"empId":111,"empName":"Aria","empStatus":"No","dob":"1995-10-17","age":20}
]如何更改代码,以便将JSON字符串正确转换为Knockout.js可观察数组?
发布于 2015-07-15 09:00:09
做下面的事情
var json = [{"empId":100,"empName":"TA","empStatus":"yes","dob":"2000-12-12","age":15},{"empId":101,"empName":"TA","empStatus":"yes","dob":"2000-12-12","age":15},{"empId":102,"empName":"TATA","empStatus":"yes","dob":"1997-12-12","age":18},{"empId":103,"empName":"kljh","empStatus":"yes","dob":"2000-12-12","age":15},{"empId":111,"empName":"Aria","empStatus":"No","dob":"1995-10-17","age":20}]
var ViewModel = function() {
this.list = ko.observable(ko.mapping.fromJS(json)());
console.log(this.list());
};
ko.applyBindings(new ViewModel()); 在视图中,按照视图结构使用$data而不是$parent。
工作样本小提琴这里
https://stackoverflow.com/questions/31422720
复制相似问题