【问题标题】:How to save a model to database? [duplicate]如何将模型保存到数据库? [复制]
【发布时间】:2016-10-30 18:28:30
【问题描述】:

您好,我正在尝试将模型保存到数据库。我只是输入标题的值来保存它,因为我的 id 是自动递增的。我已经尝试过了,但没有奏效。谁能帮帮我?

我需要在我的主干模型中指定什么 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');
        }
    });
}

【问题讨论】:

    标签: javascript jquery ajax backbone.js


    【解决方案1】:

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

    如果模型isNew,则保存为“create”(HTTP POST),如果模型已存在于服务器上,则保存为“update”(HTTP @987654327 @)。

    代码:

    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);
        }
    });
    

    【讨论】:

    • 谢谢你,但我需要在模型中输入什么网址?我的集合的 URL 与所有模型的 json 响应或?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    • 2015-03-17
    相关资源
    最近更新 更多