Backbone.js を使用して ajax 経由で html テーブルをレンダリングしてみます。
Ajax リクエストは正常に機能し、JSON データを返しますが、json がモデルと一致していないように見えます。
私はSymfonyとSerialize Bundleを使用しています。
これは私のバックボーン モデルとコレクションです。
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":"メイラ、アリエル・ジャーム\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();