杰森和淘汰赛

时间:2012-06-01 01:46:17

标签: ajax json knockout.js

我有一张表“应该”与json的结果绑定,但它不起作用,可能是错误?

<table>
<thead>
    <tr>
        <th>
            Id
        </th>
        <th>
            Number
        </th>
        <th>
            Name
        </th>
        <th>
            Password
        </th>
        <th>
            Role
        </th>
    </tr>
</thead>
<tbody data-bind="foreach: model.Employees">
    <tr>
        <td>
            <span data-bind="text: EmployeeId"></span>
        </td>
        <td>
            <span data-bind="text: EmployeeNumber"></span>
        </td>
        <td>
            <span data-bind="text: EmployeeName"></span>
        </td>
        <td>
            <span data-bind="text: EmployeePassword"></span>
        </td>
        <td>
            <span data-bind="text: EmployeeRole"></span>
        </td>
    </tr>
</tbody>

我的淘汰剧本是这样的:

<script type="text/javascript">
$(document).ready(function () {
    var viewModel = {};
    var data = $.getJSON("Employees.json", function (data) {
        viewModel= ko.mapping.fromJSON(data);
        ko.applyBindings(viewModel);
    }
    );
});
</script>

这是我的样本返回的json数据:

 {"Employees":[{"EmployeeId":1,"EmployeeName":X","EmployeeNumber":"1","EmployeePassword":"x","EmployeeRole":"User"},{"EmployeeId":10,"EmployeeName":"S","EmployeeNumber":"21","EmployeePassword":"s","EmployeeRole":"Admin"}]}

1 个答案:

答案 0 :(得分:4)

如果你打开浏览器的错误控制台我打赌你会看到这样的事情:

  

未捕获错误:无法解析绑定。消息:ReferenceError:   员工没有定义;绑定价值:foreach:员工

<{1}}未定义

Employees。但是,它是在viewModel上定义的。如果您要么: - / p>

  1. viewModel.model data-bind上的foreach代替:

    model.Employees

    示例: http://jsfiddle.net/Ze2Zs/

  2. 将AJAX请求的结果直接分配给<tbody data-bind="foreach: model.Employees"> 而不是viewModel

    viewModel.model

    示例: http://jsfiddle.net/wHXeP/

  3. 另外作为旁注,不需要分配viewModel = ko.mapping.fromJSON(data); ,因为回复函数处理了响应:

    var data = $.getJSON(...)