将json字符串转换为knockout observable array

时间:2015-07-15 06:13:05

标签: javascript json knockout.js

我正在尝试将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可观察数组?

1 个答案:

答案 0 :(得分:2)

执行以下操作

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

工作样本小提琴 here