【问题标题】:How can I output the JSON?如何输出 JSON?
【发布时间】:2014-02-22 18:10:29
【问题描述】:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
    <link href="/bundles/hoaxpartner/css/style.css" type="text/css" rel="stylesheet" />
</head>
    <body>

    <div id="header">Backbone</div>
    <div id="sidebar"></div>
    <div id="content"></div>

    <script type="text/template" id="tpl-user-list-item">
        <a href='#users/<%= id %>'><%= name %></a>
    </script>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js"></script>

    <script>

        window.User = Backbone.Model.extend();

        window.UserCollection = Backbone.Collection.extend({
            model: User,
            url: "/app_dev.php/api/users/1/",
            parse : function(resp) {
                /*
                $.each(resp.users, function(key1, value1) {
                    resp.users[key1] = $.map(value1, function(value2, key2) { 
                        return [value2];
                    });
                });
                */
                return resp.users;
            },
        });

        // Views
        window.UserListView = Backbone.View.extend({

            tagName:'ul',

            initialize:function () {
                this.model.bind("reset", this.render, this);
            },

            render:function (eventName) {
                _.each(this.model.models, function (user) {
                    $(this.el).append(new UserListItemView({model:user}).render().el);
                }, this);
                return this;
            }

        });

        window.UserListItemView = Backbone.View.extend({

            tagName:"li",

            template:_.template($('#tpl-user-list-item').html()),

            render:function (eventName) {
                $(this.el).html(this.template(this.model.toJSON()));
                return this;
            }

        });

        // Router
        var AppRouter = Backbone.Router.extend({

            routes:{
                "":"list"
            },

            list:function () {
                this.userList = new UserCollection();
                this.userListView = new UserListView({model:this.userList});
                this.userList.fetch();
                $('#sidebar').html(this.userListView.render().el);
            }

        });

        $(function() {
            var app = new AppRouter();
            Backbone.history.start();
        });

    </script>

</body>
</html>

/app_dev.php/api/users/1 调用输出:

{
  "users": [
    {
      "userid": "Jf9CEy70",
      "password": "g5JY9OB2",
      "status_id": 1,
      "created": "2014-01-13 18:33:25"
    },
    {
      "userid": "8LZVQX6b",
      "password": "QFzO92tM",
      "status_id": 1,
      "created": "2014-01-13 18:35:00"
    },
    {
      "userid": "cItWduq9",
      "password": "SuzcWisl",
      "status_id": 0,
      "created": "2014-01-13 18:35:21"
    }
  ]
}

数据是从“/app_dev.php/api/users/1” API 接收的,但我一直在显示它。

【问题讨论】:

    标签: javascript json backbone.js


    【解决方案1】:

    1- 尝试将此功能添加到您的收藏中:

    parse : function(resp) {
        return resp.users;
    }
    

    因为您的集合正在等待一个模型数组,但它得到了一个对象。

    2- 将这个this.collection.on('change', this.render, this); 更改为这个this.collection.on('reset', this.render, this);,因为当集合从服务器接收数据时,它会触发reset 事件(触发change 的是模型)

    3- 添加这一行

    this.collection = new App.Collections.Models();
    

    在这一行之前

    view = new App.Views.ModelsIndex({'collection': this.collection});
    

    因为你在使用this.collection 时没有初始化它。

    4- 将您的App.Views.ModelsIndex 中的tagName 更改为el,并为其指定要在其中呈现模板的 div ('#someEl')

    更新

    你的新问题是模板,你有一些错误(userId而不是id,你的json中没有名字),这是一个有效的:

    <script type="text/template" id="tpl-user-list-item">
        <a href = '#users/<%= userid %>' ><%= created %></a>
    </script>
    

    【讨论】:

    • 真倒霉!我花了几天时间,但无法让它工作。我发布了完全不同的代码。同样的问题。我被困住了。
    • 我已经更新了我的答案,测试了它并且它正在工作
    【解决方案2】:

    因为this.collection.fetch();是异步的,所以如果你在initialize中调用它,然后立即调用index,此时的集合还没有被“获取”。您应该更改代码以正确处理异步调用

    另一件事是您正在侦听change 事件,该事件在集合中的每个模型发生更改时应用,您应该侦听reset 事件(如果您想在获取后重置模型)或@ 987654327@(如果我没记错的话)

    另一个可能有用的事件是request,它将在发送 ajax 请求后立即触发

    更新: 所以在这种情况下,你可以改变

    this.collection.on('change', this.render, this);
    

    this.collection.on('sync', this.render, this);
    

    然后移动

    this.collection.fetch();
    

    到之后

    view = new App.Views.ModelsIndex({'collection' : this.collection});
    

    【讨论】:

    • 感谢您的提示!也许我猫得到通知?什么是正确的解决方案?
    • 刚刚添加了(可能是)解决方案
    • 谢谢!我已经尝试过了,但没有任何改变。问题已更新,因此您可以随时查看。
    • 这个怎么样 (pastebin.com/02swkthp)。好像您错误地启动了集合new App.Routers.Models();,而您的集合是App.Collections.Models
    猜你喜欢
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多