[英]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.