2016-06-28 97 views
-2

你好我试图将模型保存到数据库。我只是输入一个标题的值来保存它,因为我的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'); 
     } 
    }); 
} 

回答

0

可以使用骨干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); 
    } 
}); 
+0

感谢,但我需要的网址放在模型?我收集的网址与所有模型的json响应或? – neko

相关问题