JSON не соответствует модели

Я пытаюсь отобразить таблицу html через ajax с помощью Backbone.js.

Запрос 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": ""} ...]

Но в таблице в ячейках выведите «undefined». Любые идеи ?.

ОБНОВЛЕНИЕ Спасибо за ответы. 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();

person ramiromd    schedule 14.11.2013    source источник
comment
похоже на проблему в вашем представлении, а не в вашей модели, возможно, добавьте код, отвечающий за рендеринг   -  person homtg    schedule 14.11.2013
comment
как и homtg, проблема не в этом коде. Вот jsFiddle, где вы можете увидеть, что JSON правильно проанализирован.   -  person Markinhos    schedule 16.11.2013


Ответы (1)


Я подозреваю, что проблема в том, что вы пытаетесь распечатать атрибуты модели до того, как они будут получены с сервера. Попробуй это:

var App = Backbone.View.extend({

    // Base the view on an existing element
    el: $('#table-sessions'),

    initialize: function(){

        this.list = $('#sessions');
        this.collection = new AuditoriaList
        var that = this;
        this.collection.fetch({
            success: function(collection) {
               collection.each(function(sesion) {
                  var view = new AuditoriaView({ model: sesion });
                  that.list.append(view.render().el);
               });
            }
        });
        this.listenTo(this.collection, 'change', this.render);
    },

    render: function(){
        return this;
    }
});
person Markinhos    schedule 18.11.2013