我该如何输出JSON?

时间:2014-01-30 12:26:30

标签: javascript json backbone.js

<!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,但我一直坚持显示它。

2 个答案:

答案 0 :(得分:0)

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

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

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

2-通过此this.collection.on('change', this.render, this);更改此ligne this.collection.on('reset', this.render, this);,因为当集合从服务器接收数据时,它会触发reset事件(触发的模型{{1} }})

3-添加此行

change

在此行之前

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

因为您使用view = new App.Views.ModelsIndex({'collection': this.collection}); 而未初始化它。

4-将this.collection中的tagName更改为App.Views.ModelsIndex并将其提供给您希望呈现模板的div(el

更新

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

'#someEl'

答案 1 :(得分:0)

因为this.collection.fetch();是异步的,所以如果你在initialize中调用它然后立即调用index,那么此时的集合不会被提取&#34;然而。您应该更改代码以正确处理异步调用

另一件事是你在监听集合中每个模型发生变化时应用的change事件,你应该监听reset事件(如果你想在之后重置模型)提取)或sync(如果我没记错的话)

另一个可能有用的事件是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});