Backbone.js - 获取数据并显示

eri*_*bae 8 backbone.js

我刚刚开始使用Backbone.js.这是我的代码.

$(function(){

    //Backbone Model
    var Cat = Backbone.Model.extend({});

    // create a collection
    var CatCollection = Backbone.Collection.extend({
        model: Cat,
        url: 'http://localhost/cats/index.php/cats/index'
    });
    var catCollection = new CatCollection();
    catCollection.fetch();

    // Backbone view
    var CatView = Backbone.View.extend({
        el: $("#contents"),
        initialize: function() {
            this.render();
        },
        render: function() {
            this.el.html(catCollection);
        }
    });

    var catView = new CatView();
});
Run Code Online (Sandbox Code Playgroud)

我在做什么.

  1. 创建骨干模型
  2. 使用我创建的模型创建集合.
  3. 从MySQL数据库获取数据 - 这将返回一个JSON数据对象.
  4. 在div"#contents"中显示获取的数据.

在谷歌浏览器上,我可以看到"fetch()"方法有效,因为我可以看到我的JSON对象返回为

[{"id":"1","name":"stella","age":"5"},{"id":"2","name":"Max","age":"2"}]
Run Code Online (Sandbox Code Playgroud)

但如果我在获取后执行"alert(catCollection)",则会显示"[object] [object]".

显示此内容的最佳方式是什么?

ska*_*red 3

您应该使用 JST 数组中的模板。

$(this.el).html($(JST["comments/item"](model.toJSON())));
Run Code Online (Sandbox Code Playgroud)

“comments\item”是模板路径和名称如果您使用Rails,只需使用Jammit并使用ERB(默认)或Jade编写模板