如何将模型保存到数据库?

时间:2016-06-28 12:16:23

标签: javascript jquery ajax backbone.js

您好我试图将模型保存到数据库。我只是输入标题的值来保存它,因为我的id是自动增量。我试过了,但它没有奏效。任何人都可以帮助我吗?

我需要在Backbone模型中指定什么urlRoot或url函数?我是否需要指定我的收藏集的网址?

型号:

var DocumentUser = Backbone.Model.extend({
    urlRoot: '/app_dev.php/user'
});

这是我的保存功能:

save: function(method, model, options) {
    this.model = new DocumentUser();
    this.model.save({
        title: $('#title').val()
    }, {
        success: function(model, respose, options) {
            console.log('The model has been saved to the server');
        },
        error: function(model, xhr, options) {
            console.log('Something went wrong while saving the model');
        }
    });
}

1 个答案:

答案 0 :(得分:0)

您可以使用Backbone model.save([attributes], [options]) 将模型保存到您的数据库(或替代持久层),方法是委派给Backbone.sync

如果型号为isNew,则保存将为" create" (HTTP POST),如果模型已存在于服务器上,则保存将是" update" (HTTP PUT)。

代码:

var DocumentUser = Backbone.Model.extend({
        default: {
            title: ''
        },
        urlRoot: '/app_dev.php/user'
    }),
    documentUser = new DocumentUser();

documentUser.save({
    title: $('#title').val()
}, {
    success: function(response) {
        console.log('The model has been saved to the server', response);
    },
    error: function(response) {
        console.log('Something went wrong while saving the model', response);
    }
});