【问题标题】:knockout.mapping to access an array inside jsonknockout.mapping 访问 json 中的数组
【发布时间】:2012-04-17 13:53:25
【问题描述】:

这是我下面的例子。 我在我的项目中使用了 knockout.mapping 插件。

我想将邮件数组中的“发件人”元素填充到我的未排序列表中:

在注释代码中,我添加了使用 jquery ajax 从数据库中检索的数据。

<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="js/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script src="js/knockout-2.0.0.debug.js" type="text/javascript"></script>
    <script src="js/KnockoutMapping2.1.1.js" type="text/javascript"></script>
    <script type="text/javascript">

        $(document).ready(function () {
            var viewModel = {};

            $.ajax({
                url: "Service.aspx",
                type: 'POST',
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    //data :
                    //       {
                    //   "id":"Inbox",
                    //   "mails":[
                    //      {
                    //         "id":"1",
                    //         "from":"Abbot ",
                    //         "to":"steve@example.com",
                    //         "date":"May 25, 2011",
                    //         "subject":"Booking confirmation #389629244",
                    //         "folder":"Inbox"
                    //      }
                    //   ]
                    //}
                    viewModel = ko.mapping.fromJS(data);

                    ko.applyBindings(viewModel);
                },
                error: function (request) {
                    alert(request.responseText);
                }
            });




        });
    </script>
</head>
<body>
    your id is : <span data-bind='text: id' />
    <ul data-bind="foreach : mails">
        <li data-bind="value:from"></li>
    </ul>
</body>
</html>

任何将邮件绑定到我的列表的帮助。

【问题讨论】:

    标签: knockout.js knockout-mapping-plugin


    【解决方案1】:

    http://jsfiddle.net/nickolsky/EVaPL/

    your id is : <span data-bind='text: id' ></span>
        <ul data-bind="foreach : mails">
            <li data-bind="text:from"></li>
    
    1. 不要自闭合跨度 (Can a span be closed using <span />?)
    2. 对 li 使用文本绑定而不是值绑定

    【讨论】:

    • 自闭标签之前也曾咬过我。显然 html != xml
    【解决方案2】:

    http://jsfiddle.net/ryanwfiorini/DmWYS/

    我整理了一个fiddle 给你看看我喜欢怎么做。我喜欢创建一个类来保存我的数据,从而允许对它进行更多控制。您可以将它们包含连接等功能。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      相关资源
      最近更新 更多