骨干解析JSON响应

骨干解析JSON响应

本文介绍了骨干解析JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用了共3天骨干,现在,我可以看到,这已经被问了很多,但老实说,我只是没有得到它。我一直在敲打我的头撞墙试图让运行解析嵌套的JSON一个基本的应用程序,我似乎无法去解决它。如果我扁平化的JSON响应,并删除嵌套元素这一切工作,但是这不是我怎么会接受它。

我试着骨干关系的一些例子,但我真的被困在这里,共骨干的n00b,并希望一些帮助。

下面是HTML:

 < D​​IV ID =员工数据>
    <脚本类型=文/模板ID =员工模板>
        < OL ID =数据块>
        < / OL>
        < D​​IV CLASS =清除>< / DIV>
    < / SCRIPT>
    <脚本类型=文/模板ID =员工模板>
        < H2>您的雇主:LT;跨度><%= employerName%GT;< / SPAN> < / H>
        < D​​IV>员工编号:LT;跨度><%=雇员%GT; < / SPAN>< / DIV>
        < D​​IV>名称:LT;跨度><%= employeeName%GT; < / SPAN>< / DIV>
        &所述; DIV>标题:或其可跨度>&下;%= employeeJobTitle%GT; < / SPAN>< / DIV>
        < D​​IV>地点:<跨度><%= employeeLocation%GT; < / SPAN>< / DIV>
    < / SCRIPT>
< / DIV>

这里是JS:

  VAR联系= {
    楷模: {},
    类别:{},
    浏览次数:{},
   模板:{}
}Contact.Models.Employee = Backbone.RelationalModel.extend({});Contact.Collections.Employees = Backbone.Collection.extend({
    型号:Contact.Models.Employee,
    网址:包括/测试data.json    初始化:功能(){
        的console.log(员工初始化);
    }
});Contact.Templates.employees = _.template($(#员工模板)HTML());Contact.Views.Employees = Backbone.View.extend({
    EL:$(#员工数据),
    模板:Contact.Templates.employees,    初始化:功能(){
       this.collection.bind(复位,this.render,这一点);
       this.collection.bind(增加,this.addOne,这一点);
    },    渲染:功能(){
        的console.log(渲染)
        的console.log(this.collection.length);
        $(this.el)的.html(this.template());
        this.addAll();
    },    的addAll:功能(){
       的console.log(的addAll)
       this.collection.each(this.addOne);
    },    addOne:函数(模型){
       的console.log(addOne)
       鉴于=新Contact.Views.Employee({模式:模式});
       $(OL,this.el).append(view.render());
    }})
Contact.Templates.employee = _.template($(#员工模板)HTML());Contact.Views.Employee = Backbone.View.extend({
    标签名:礼
    模板:Contact.Templates.employee,    初始化:功能(){
        this.model.bind('破坏',this.destroyItem,这一点);
        this.model.bind(删除,this.removeItem,这一点);
    },    渲染:功能(){
        返回$(this.el).append(this.template(this.model.toJSON()));
    }
})
Contact.Router = Backbone.Router.extend({
    路线:{
        :默认路由
    },    默认路由:功能(){
        的console.log(默认路由);
        Contact.employees =新Contact.Collections.Employees();        新Contact.Views.Employees({集合:Contact.employees}); //添加此行        Contact.employees.fetch({
        错误:功能(响应,XHR){
            的console.log(响应);
            的console.log(XHR)
        },
        成功:函数(){
            的console.log(成功);
        }
    });
        的console.log(Contact.employees.length)
    }
})VAR appRouter =新Contact.Router();Backbone.history.start();

最后的JSON:

  [
    {
  的ContactID:345345234,
  雇员 : [ {
    雇员:EE-00000001,
    employeeName:布巴浩TEP
    employeeLegalFirstName:布巴,
    员工prefFirstName:,
    employeeLastName:何-TEP
    employeeMaritalStatus:单次,
    employeeBirthYear:1942年,
    employeeJobTitle:,
    employmentStatus:活动,
    employmentTerminationDte:,
    employeeReference code:EE1
    employeeDivision:HR,
    employeeLocation:市区,
    employeeEmail:[email protected]
    雇主:{
      employerId:ER-00000001,
      employerName:Initech的
    }
  }]
}
]


解决方案

您应该使用您系列:

  Contact.Collections.Employees = Backbone.Collection.extend({
    型号:Contact.Models.Employee,
    网址:包括/测试data.json    初始化:功能(){
        的console.log(员工初始化);
    },    解析:功能(响应){
        返回response.employees;
   }});

有一个解析()在模型中,以及在集合,关于URL()处理同样的目的。

编辑:
我不是在路由器的专家,但我想你要呈现在某些时候查看。

  VAR视图=新Contact.Views.Employees({集合:Contact.employees});
view.render();

I've been using Backbone for a total of 3 days now, and I can see that this has been asked about quite a lot, but honestly I'm just not getting it. I've been banging my head against the wall trying to get a basic app running parsing nested json and I just can't seem to work it out. It all works if I flatten out the json response, and remove the nested elements, but that's not how I will receive it.

I've tried some examples with Backbone relational, but I'm really stuck here, a total backbone n00b, and hoping for some help.

Here is the HTML:

<div id="employee-data">
    <script type="text/template" id="employees-template">
        <ol id="data-block">
        </ol>
        <div class="clear"></div>
    </script>
    <script type="text/template" id="employee-template">
        <h2>Your employer: <span><%= employerName %></span> </h2>
        <div>Employee Id: <span><%= employeeId %> </span></div>
        <div>Name: <span><%= employeeName %>     </span></div>
        <div>Title: <span><%= employeeJobTitle %> </span></div>
        <div>Location: <span><%= employeeLocation %> </span></div>
    </script>
</div>

Here is the js:

var Contact = {
    Models: {},
    Collections: {},
    Views: {},
   Templates:{}
}

Contact.Models.Employee = Backbone.RelationalModel.extend({});

Contact.Collections.Employees = Backbone.Collection.extend({
    model: Contact.Models.Employee,
    url: "includes/test-data.json",

    initialize: function(){
        console.log("Employees initialize");
    }
});

Contact.Templates.employees = _.template($("#employees-template").html());

Contact.Views.Employees = Backbone.View.extend({
    el: $("#employee-data"),
    template: Contact.Templates.employees,

    initialize: function () {
       this.collection.bind("reset", this.render, this);
       this.collection.bind("add", this.addOne, this);
    },

    render: function () {
        console.log("render")
        console.log(this.collection.length);
        $(this.el).html(this.template());
        this.addAll();
    },

    addAll: function () {
       console.log("addAll")
       this.collection.each(this.addOne);
    },

    addOne: function (model) {
       console.log("addOne")
       view = new Contact.Views.Employee({ model: model });
       $("ol", this.el).append(view.render());
    }

})


Contact.Templates.employee = _.template($("#employee-template").html());

Contact.Views.Employee = Backbone.View.extend({
    tagName: "li",
    template: Contact.Templates.employee,

    initialize: function () {
        this.model.bind('destroy', this.destroyItem, this);
        this.model.bind('remove', this.removeItem, this);
    },

    render: function () {
        return $(this.el).append(this.template(this.model.toJSON())) ;


    }
})


Contact.Router = Backbone.Router.extend({
    routes: {
        "": "defaultRoute"
    },

    defaultRoute: function () {
        console.log("defaultRoute");
        Contact.employees = new Contact.Collections.Employees();

        new Contact.Views.Employees({ collection: Contact.employees }); //Add this line

        Contact.employees.fetch({
        error:function(response, xhr){
            console.log(response);
            console.log(xhr)
        },
        success:function(){
            console.log("success");
        }
    });
        console.log(Contact.employees.length)
    }
})

var appRouter = new Contact.Router();

Backbone.history.start();

And finally the json:

[
    {
  "contactId" : "345345234",
  "employees" : [ {
    "employeeId" : "EE-00000001",
    "employeeName" : "BubbA Ho-tep",
    "employeeLegalFirstName" : "Bubba",
    "employeePrefFirstName" : "",
    "employeeLastName" : "Ho-tep",
    "employeeMaritalStatus" : "Single",
    "employeeBirthYear" : "1942",
    "employeeJobTitle" : "",
    "employmentStatus" : "Active",
    "employmentTerminationDte" : "",
    "employeeReferenceCode" : "EE1",
    "employeeDivision" : "HR",
    "employeeLocation" : "Downtown",
    "employeeEmail" : "[email protected]",
    "employer" : {
      "employerId" : "ER-00000001",
      "employerName" : "Initech"
    }
  } ]
}
]
解决方案

You should use the parse() method in your collection :

Contact.Collections.Employees = Backbone.Collection.extend({
    model: Contact.Models.Employee,
    url: "includes/test-data.json",

    initialize: function(){
        console.log("Employees initialize");
    },

    parse : function(response){
        return response.employees;
   }

});

There is one parse() in the MOdel as well as in the Collection, for the same purpose on url() handling.

EDIT :I'm not an expert in the Router, but I suppose you have to render the View at some point.

var view = new Contact.Views.Employees({ collection: Contact.employees });
view.render();

这篇关于骨干解析JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 21:46