我四处搜索,发现比我需要做的更复杂的例子。
我有一个 PHP 页面 (data.php),它查询 MYSQL 数据库并返回 3 名员工的 JSON。
在下面的代码中,我对返回的 JSON 示例进行了硬编码,整个过程按预期工作。
我想知道的是用加载时从 data.php 获取的 JSON 替换下面的硬编码 JSON 的最简单方法是什么。
// Model
Person = Backbone.Model.extend({
defaults: {
first_name: 'John',
last_name: 'Doe',
department: 'Corporate',
title: 'Admin'
}
});
// List of People
var PeopleCollection = Backbone.Collection.extend({
model: Person
});
var PeopleView = Backbone.View.extend({
tagName: 'ul',
render: function(){
this.collection.each(function(person){
var personView = new PersonView({model: person});
this.$el.append(personView.render().el);
}, this);
return this;
}
});
// The View for a Single Person
var PersonView = Backbone.View.extend({
tagName: 'li',
template: _.template( $('#personTemplate').html() ),
render: function() {
this.$el.html( this.template(this.model.toJSON()) );
return this;
}
});
var peopleCollection = new PeopleCollection(
[{"first_name":"Jodie","last_name":"Smith","short_name":"SmithJ","department":"Creative","phone":"3446","start_date":"0000-00-00","end_date":"0000-00-00","active":"1","title":"Web Design Director","id":"492"},{"first_name":"Michael","last_name":"Johnson","short_name":"JohnsonM","department":"Interactive","phone":"3761","start_date":"0000-00-00","end_date":"0000-00-00","active":"1","title":"Sr. Director, Interactive","id":"569"},{"first_name":"Frank","last_name":"Thomas","short_name":"ThomasF","department":"Distribution","phone":"3516","start_date":"0000-00-00","end_date":"0000-00-00","active":"1","title":"Warehouse Coordinator","id":"454"}]
);
var peopleView = new PeopleView({ collection: peopleCollection });
$(document.body).append(peopleView.render().el)