我尝试使用 Backbone.js 通过 ajax 渲染一个 html 表。
Ajax 请求工作正常,返回 JSON 数据,但显示 json 与模型不匹配。
我正在使用 Symfony 和 Serialize Bundle。
这是我的 Backbone 模型和收藏:
var Auditoria = Backbone.Model.extend({
defaults:{
id: 'undefined',
user_id: 'undefined',
user_str: 'undefined',
user_agent: 'undefined',
login_from: 'undefined',
login_date: 'undefined'
}
});
var AuditoriaList = Backbone.Collection.extend({
model: Auditoria,
url: $("#ajax-call").val()
});
var sesiones = new AuditoriaList();
sesiones.fetch({
async: false
});
Ajax 响应(写在 Symfony 上)会:
public function getSesionesAction(){
$em = $this->getDoctrine()->getManager();
$sesiones_registradas = $em->getRepository('AuditBundle:AuditSession')->findAll();
$serializer = $this->get('jms_serializer');
// Prepara la respuesta
$response = new Response();
$response->setContent($serializer->serialize($sesiones_registradas,'json'));
$response->headers->set('Content-Type', 'text/json');
// Retorna la respuesta
return $response;
}
返回的 JSON 数据为:
[{"id":4,"user_id":1046,"user_str":"Meyra, Ariel Germ\u00e1n","login_date":"2013-11-11 10:24:12","user_agent":"" ,"login_from":""} ... ]
但在表格中,在单元格中打印“未定义”。有任何想法吗 ?。
更新 感谢您的回复。HTML 视图是下一个:
<table id="table-session" class="table table-bordered table-hover">
<thead>
<tr>
<th>#</th>
<th># Usuario</th>
<th>Usuario</th>
<th>Navegador</th>
<th>Desde</th>
<th>Fecha</th>
</tr>
</thead>
<tbody id="sessions">
</tbody> </table>
并且渲染 Backnone 是:
var AuditoriaView = Backbone.View.extend({
tagName: 'tr',
initialize: function(){
// Cada vez que el modelo cambie, vuelve a renderizar
this.listenTo(this.model, 'change', this.render);
},
render: function(){
this.$el.html("<td>" + this.model.get('id') + "</td>" + "<td>" + this.model.get('user_id') + "</td>"
+ "<td>" + this.model.get('user_str') + "</td>" + "<td>" + this.model.get('user_agent') + "</td>"
+ "<td>" + this.model.get('login_from') + "</td>" + "<td>" + this.model.get('login_date') + "</td>"
);
return this;
}
});
// The main view of the application
var App = Backbone.View.extend({
// Base the view on an existing element
el: $('#table-sessions'),
initialize: function(){
this.list = $('#sessions');
this.listenTo(sesiones, 'change', this.render);
sesiones.each(function(sesion){
var view = new AuditoriaView({ model: sesion });
this.list.append(view.render().el);
}, this);
},
render: function(){
return this;
}
});
new App();