javascript Backbone model.save() 正在发送 PUT 而不是 POST
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13384448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Backbone model.save() is sending PUT instead of POST
提问by Rail24
I call save using this:
我用这个调用保存:
console.log(this.model.isNew());
console.log(this.model);
this.model.save({}, {
success: function (model, response, options) {
console.log(response);
},
error: function (model, xhr, options) {
console.log(xhr.result.Errors);
}
});
The isNew()
returns false. But the output of this.model
has an ID of 0. (this.model.id is 0 as well)
在isNew()
返回false。但是输出this.model
的ID为0。(this.model.id也是0)
My url is url: ROOTAREA + "/Expenses/Entry/",
我的网址是 url: ROOTAREA + "/Expenses/Entry/",
Updating works fine, and uses PUT as expected.
更新工作正常,并按预期使用 PUT。
Edit : here's part of my model:
编辑:这是我模型的一部分:
defaults: function () {
return {
DocumentDate: "",
JobNo_: "",
PhaseCode: "",
WorkTypeCode: "",
Description: "",
Quantity: 0,
UnitCost: 0,
ExpenseCurrencyCode: "",
ReimbursementCurrencyCode: "",
UnitofMeasureCode: "DIEM",
LineNo_: 0
};
},
idAttribute: "LineNo_",
回答by tonino.j
ID should not even exist for a new entry. The issue is in the part you didn't show - in the part where you instantiate, create and populate the model.
新条目甚至不应该存在 ID。问题在于您没有显示的部分 - 在您实例化、创建和填充模型的部分。
Here is a quote from the Backbone documentation:
这是Backbone 文档中的引述:
If the model does not yet have an
id
, it is considered to be new.
如果模型还没有
id
,则认为它是新的。
It is clear from your code that you are assigning an id attribute.
Your backend should be doing that.
And since you are doing it on a client, backbone presumes it it not new, and uses PUT
从您的代码中可以清楚地看出您正在分配一个 id 属性。您的后端应该这样做。并且由于您是在客户端上执行此操作,因此主干假定它不是新的,并使用PUT
回答by Lane
The above answers are correct in that if the model
you are .save
'ing has an id
attribute backbone will do a PUT
rather than a POST
.
上面的答案是正确的,因为如果model
你.save
有一个id
属性主干将做 aPUT
而不是 a POST
。
This behavior can be overridden simply by adding type: 'POST'
to your save block:
只需添加type: 'POST'
到您的保存块即可覆盖此行为:
var fooModel = new Backbone.Model({ id: 1});
fooModel.save(null, {
type: 'POST'
});
回答by seppestaes
You can specify the ID in defaults, just make sure it's set to null
(isNew will be set to true).
您可以在默认值中指定 ID,只需确保将其设置为null
(isNew 将设置为 true)。
In your case it must be
在你的情况下,它必须是
LineNo_: null