简体   繁体   English

如何输出JSON?

[英]How can I output the JSON?

<!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 call output: /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"
    }
  ]
}

The data is received from "/app_dev.php/api/users/1" API, but I'm stuck on displaying it. 数据是从“ /app_dev.php/api/users/1”API接收的,但是我一直坚持显示它。

1- Try to add this function to your collection : 1-尝试将此功能添加到您的收藏中:

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

Because your collection is waiting an array of models, but it gets an object. 因为您的集合正在等待模型数组,但它得到一个对象。

2- Change this ligne this.collection.on('change', this.render, this); 2-更改此ligne this.collection.on('change', this.render, this); by this one this.collection.on('reset', this.render, this); 通过这个this.collection.on('reset', this.render, this); , because when the collection receive the data from the server it trigger a reset event (it's the Model that trigger change ) ,因为当集合从服务器接收数据时,它将触发一个reset事件(触发change的是Model)

3- Add this line 3-添加此行

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

before this line 在这行之前

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

Because you are using this.collection without initializing it. 因为您使用的是this.collection而不进行初始化。

4- Change the tagName in your App.Views.ModelsIndex to el and give it the div where you want your template to be rendered ( '#someEl' ) 4-将App.Views.ModelsIndextagName更改为el并为它提供要呈现模板的位置的div( '#someEl'

UPDATE UPDATE

Your new problem is the template, you have some errors in it (userId instead of id, there is no name in your json), here is a working one : 您的新问题是模板,模板中有一些错误(userId代替id,json中没有名称),这是一个有效的模板:

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

Because this.collection.fetch(); 因为this.collection.fetch(); is asynchronous, so if you call it in initialize and then call index immediately, the collection at this time is not "fetched" yet. 是异步的,因此,如果您在initialize调用它,然后立即调用index ,则此时尚未“获取”该集合。 You should change your code to properly handle asynchronous calls 您应该更改代码以正确处理异步调用

Another thing is that you are listening to change event which is applied when there are changes for each model in the collection, you should listen to reset event (if you want to reset the model after fetching) or sync (if I remember correctly) 另一件事是,您正在侦听change事件,该事件在集合中的每个模型都有更改时应用,您应该侦听reset事件(如果要在获取后重置模型)或sync (如果我没记错的话)

Another event that might be useful is request which will be fired as soon as the ajax request is sent 另一个可能有用的事件是request ,该request将在发送ajax请求后立即触发

Updated: So in this case, you can change 更新:因此,在这种情况下,您可以更改

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

to

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

And move 并移动

this.collection.fetch();

To after 到之后

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM