1

我正在使用骨干。我有一个json数据,例如:

{"status": 7, 
 "organizations":[{"org_address":"\u4e2d\u56fd\u5317\u4eac\u5e02\u671d\u9633\u95e8\u59161001\u53f7", "job_positions": ["\u526f\u603b"], "org_id": 6, "org_name": "\u6570\u7ef4\u7f51\u7edc"}], "first_name": null, "last_name": null, "create_date": "2013-06-26 16:29:44.314000", "name": "\u66f9\u4f1f", "extra_emails": [null], "tags": [["friend"]], "nick_name": "\u4f11\u606f\u4e00\u4f1a\u513f", "gender": "\u7537", "image": null, "created_by": "system", "effective_start_date": "2013-06-26 16:29:44.314000", "social_medias": [{"url": "http://weibo.com/12345", "party_rel_id": 5, "type": "\u65b0\u6d6a\u5fae\u535a", "party_id": null, "sm_id": "\u6570\u636e\u5e93\u4e13\u5bb6"}], "date_of_birth": "1980-04-01", "extra_phones": {"office_phone": "82323333", "fax": "82324433"}, "mobile_phone": "17782272211", "primary_email": "weic@xy.com", "id": "5", "isUser": false}

我的骨干模型是:

var ContactDetail = Backbone.Model.extend({  
    urlRoot: URL_CONTACTS1+"3/5"
});

var ContactDetailCollection =  Backbone.Collection.extend({ 
    model: ContactDetail,
    url: URL_CONTACTS1+"3/5"
})

我的主干观点是:

var ContactDetailItemView = Backbone.View.extend({
    tagName: 'div', 
    tagClass: 'border',
    template: _.template($('#contactdetail-template').html()),  
        render: function() {
        this.$el.html( this.template(this.model.toJSON()));
        return this;
    }
});
var ContactDetailListView =  Backbone.View.extend({
    el: $('#main'),
    initialize:  function(){
        this.listenTo(this.collection, 'reset', this.render);
    },  

        render: function() {
            this.$el.empty(); 
            this.collection.each( function( $model ) {
            var itemview = new ContactDetailItemView({model: $model}); 
        this.$el.append( itemview.render().el );  
            }, this);
        return this;
    },
})

入口是:

ContactDetailManagePageModel.prototype.init = function(){ 
    var myContactDetails = new ContactDetailCollection();
    contactDetailListView = new ContactDetailListView({
            collection: myContactDetails
        });     
    myContactDetails.fetch({reset:true});
}

在 html 中,我得到这样的数据:

<tr>
   <td><span class="Name_text"><%=name%></span>&nbsp;&nbsp;&nbsp;&nbsp;<%=primary_email%></td>
</tr>
<tr>
    <td><%=mobile_phone%></td>
 </tr>
 <tr>
    <td><%=org_address%></td>
 </tr>

但是我无法获取名为“org_address”的数据,它位于json数据中的对象“organizations”中,它表示“org_address”未定义。

希望得到您的帮助。谢谢!

4

2 回答 2

0

Try <%= organizations[0].org_address%>

于 2013-06-27T13:51:19.177 回答
0

当您将数据对象传递给下划线模板时,下划线会将对象属性解析为其自由变量,如果其中一个属性又是数组或本身是对象,您可以像在常规 JavaScript 中使用点一样访问它或括号符号。

因此,例如对于您的 JSON,由于组织是一个数组,并且它的第一个元素包含属性 org_address,您可以简单地执行以下操作来获取 org_address

<%=organizations[0].org_address%>

您还可以在模板中执行 JavaScript 代码,例如,如果组织包含多个组织的数组,您可以遍历它们并将它们全部打印出来。例如

<%  for (var i = 0, len = organizations.length; i < len; i++) { %>
     <tr><td>organizations[i].org_address</td></tr>
<% } %>
于 2013-06-27T14:04:41.187 回答