我在我的模型中编写了以下代码:
urlroot: '/url/sms',
setAuthId: function(value) {
var _this = this ;
if (this.get("smsauth") != value) {
this.set("smsauth",value);
this.save();
//Ideally, I want to achieve this AJAX call request with backbone.
// $.ajax({
// url: "/url/sms",
// data: value,
// type: 'PUT',
// processData: false,
// success: function(result) {
// _this.set("authId", value);
// },
// error : function(){
// console.log('Error setting authid');
// }
// });
}
},
理想情况下,我们应该每次都触发“PUT”请求。但主干网正在触发 POST 请求,因为“ID”不存在。
我对主干网还很陌生,我想知道是否有办法无需传递 ID 即可与服务器同步?我怎么解决这个问题? 我基本上想触发 PUT 请求,而不是对 URL 发布请求。(因为我的后端仅支持 PUT 请求)。
最佳答案
强制Backbone.Model.save()
执行PUT
的唯一真正方法是@dbf
解释的方式,你有设置你的 idAttribute。要正确设置 idAttribute
,您的模型应该有一个唯一的属性。 (这不是硬性要求,因为 model.isNew()
只是检查您的模型是否具有名为 id
的属性 或您提供的任何字符串到您的模型 idAttribute
属性。它不检查唯一性)。
我感觉在您的情况下,您的模型中可能没有唯一的属性,因此设置 idAttribute 可能是一个挑战。因此,我建议您不要在模型定义中指定 idAttribute
。相反,我们只是动态处理它。只需重构您的代码,如下所示:
setAuthId: function(value) {
var _this = this ;
if (this.get("smsauth") != value) {
// any model attribute is fine, we just need to return a prop
this.prototype.idAttribute = "smsauth"
this.save("smsauth",value) // Save will do a set before the server request
// model.save returns a promise. Here we'll reset the idAttribute
.then(/* success handler */ function (response) {
_this.set("authId",value);
_this.prototype.idAttribute = 'id' // You can set this to "authId" if that
// uniquely identifies this model
},/* error handler */ function (response) {
_this.prototype.idAttribute = 'id' // reset idAttribute to default
});
}
}
关于javascript - 主干同步问题触发 POST 而不是 PUT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30208543/