繁体   English   中英

读取从API REST返回的JSON对象

[英]Reading JSON Object returned from API REST

我问这个问题感觉很愚蠢,但我就像3天前一样...我建立了一个php api休息,返回一个json编码信息。 api返回的json是正确的,就是这样的:

[
    {"pk_user":"1","name":"George","surname":"Littlewolf","profile":"Game designer - Developer"},
    {"pk_user":"2","name":"Anne","surname":"Carpenter","profile":"Developer"},
    {"pk_user":"3","name":"John","surname":"Sullivan","profile":"Designer"},
    {"pk_user":"4","name":"Judith","surname":"Lenders","profile":"Developer"},
    {"pk_user":"5","name":"Jason","surname":"Middleton","profile":"Manager"}
]

在那之后,我正在创建一个攻击api的骨干前端。 我只开发了一个视图,它读取了我上面写的json。 我有一个模型(用户)和一个集合(用户) ,我想保存从json信息中读取的信息。

我将只放置视图的render函数的代码:

render: function() {
    var users = new Users();
    users.fetch();
    $.each(users['models'], function(i, item) {
        console.log(item);
    });


    this.template = _.template(template, {users : users});
    this.$el.html(this.template);
    return this;
}

现在,控制台只返回您在下一张图片中看到的内容:

在此输入图像描述

我想直接访问这些项目,但我不知道为什么,但我尝试过的所有内容都不合适...谢谢,请原谅我的新手解释...编辑

我已经将代码上传到托管给每个想要“实时”查看问题的人。

fetch是一个AJAX调用所以这个:

users.fetch();

不会立即填写收集,它必须等待服务器响应。 因此,当你去看看users.models ,那里就没有任何东西,你的观点最终什么都不做。

通常的方法是侦听来自users事件并呈现HTML以响应这些事件:

initialize: function() {
    this.collection = new Users;
    this.listenTo(this.collection, 'reset', this.render);
    // bind to other events as needed...
    this.users.fetch({ reset: true });
},
render: function() {
    this.collection.each(function(user) {
        // render the `user` model in here...
    });
}

注意切换到this.collection.each而不是直接搞乱集合的models属性。

或者,在调用fetch时使用成功处理程序:

this.users.fetch({
    success: function(collection) {
        collection.each(function(user) {
            // render the `user` model in here...
        });
    }
});

不确定它是否是您想要的,但如果您想记录用户的属性,请执行以下操作:

$.each(users['models'], function(i, item) {
    console.log(item.attributes);
});

暂无
暂无

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

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