1

我有一个“应该”与 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"}]}
4

1 回答 1

4

如果您打开浏览器的错误控制台,我敢打赌您会看到如下内容:

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

Employees上没有定义viewModel。但是,它是在 上定义的viewModel.model。如果您有以下任何一种情况,事情应该会奏效:

  1. data-bindforeachmodel.Employees改为:

    <tbody data-bind="foreach: model.Employees">
    

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

  2. 将 AJAX 请求的结果直接分配给viewModel而不是viewModel.model

    viewModel = ko.mapping.fromJSON(data);
    

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

var data = $.getJSON(...)另外作为旁注,由于响应由回调函数处理,因此无需分配:

var viewModel = {};
$.getJSON("Employees.json", function (data) {
    viewModel.model = ko.mapping.fromJSON(data);
    ko.applyBindings(viewModel);
});
于 2012-06-01T02:03:49.433 回答