简体   繁体   中英

Reading JSON Object returned from API REST

I'm feeling stupid asking the question, but I'm with it like 3 days ago... I built a php api rest, that returns a json encode info. The json that the api returns is correct, is something like that:

[
    {"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"}
]

After that, I'm creating a backbone front-end to attack the api. I have developed only one view, that reads the json I wrote above. I have one model (User) and one Collection (Users) where I'd like to save the info read from the json info.

I'm going to put only the code of the render function of the view:

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;
}

Now, the console returns only what you see in the next image:

在此输入图像描述

I'd like to access directly to the items, but i don't know why but all that I've tried is notworking... Thanks and excuse me for the newbie explanation... EDIT

I've uploaded the code to a hosting to everyone who want to see the problem "on live".

fetch is an AJAX call so this:

users.fetch();

won't fill the collection right away, it has to wait for the server to respond. So when you go to look at users.models , there won't be anything there and your view ends up doing nothing.

The usual approach is to listen for events from users and render HTML in response to those events:

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...
    });
}

Note the switch to this.collection.each instead of messing around with the collection's models property directly.

Alternatively, use a success handler when you call fetch :

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

Not sure if it is what you want, but if you want to log the attributes of the User just do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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