![](/img/trans.png)
[英]Backbone.js: model.isNew() == true, but model.save() causes POST request instead of PUT
[英]Backbone.js save model don't cause ajax PUT request on android 2.x
Phonegap + Backbone + jquery mobile。 我的Backbone模型看起来像(删除了一些代码)
var Purchase = Backbone.Model.extend({
defaults: function() {
return {
name: "",
desc: "",
shopping: null,
price:null,
quantity:1,
createdAt: new Date().getTime(),
modifiedAt: new Date().getTime()
};
}
});
var PurchaseList = Backbone.Collection.extend({
model: Purchase,
comparator: 'name'
});
var ShoppingList = Backbone.Model.extend({
defaults: function(){
return {
name:"",
totalPrice: 0,
createdAt: new Date().getTime(),
modifiedAt: new Date().getTime(),
products: new PurchaseList()
};
}
});
更新购买逻辑重新计算ShoppingList的totalPrice
save: function(position){
var data = this.$el.find("form").serializeObject();
var price = parseFloat(data.price);
var quantity = parseFloat(data.quantity);
var product = new Purchase(data);
product.on('invalid', this.showError);
var shopping = GlobalShopping.findWhere({id: data.shopping});
if(!isNaN(price) && !isNaN(quantity))
shopping.set('totalPrice', shopping.get('totalPrice') + price * quantity);
if(!isNaN(price))
product.set('price', price);
else
product.unset('price');
if(!isNaN(quantity))
product.set('quantity', quantity);
if(this.model.id){
var oldProduct = shopping.get('products').findWhere({id: this.model.id});
if(oldProduct.get('price') != null)
shopping.set('totalPrice', shopping.get('totalPrice') - oldProduct.get('price') * oldProduct.get('quantity'));
product.id = this.model.id;
product.save({}, { success: function(){
shopping.get('products').add([product], {merge: true});
shopping.save({}, {success: function(){ // <<<< issue here
window.app_router.navigate('#shopping/' + data.shopping, {replace: true, trigger: true});
}});
}});
} else {
shopping.get('products').create(product, {wait: true, success: function(){
shopping.save({}, {success: function(){
window.app_router.navigate('#shopping/' + data.shopping, {replace: true, trigger: true});
}});
}, error: function(model, xhr, options){
alert(JSON.stringify(product.toJSON()));
}});
}
}
此代码在android 4.x上可以完美运行,但在android 2.x上成功触发事件而无需PUT请求(由服务器日志检查)。
如果您查看骨干网源,则仅当您要保存的模型具有ID时,才会触发PUT请求。 您可以尝试以下方法:
product.set('id', 1);
product.save();
快速浏览一下代码,我不确定如何填充产品。 您是先获取它,然后尝试重新保存它吗? 无论如何,如果未设置Id,则Backbone将发布POST,而如果设置Id属性,则将发布PUT。 您可以像Backbone Docs一样更改您的Id Attribute属性。 我将在两个实例中都用console.log记录模型,并确保设置了相关的Id属性。
奇怪的是,它适用于android 2.x及更高版本上的android 4。 如果以上内容未能正确引导您,则可能会提供有关产品设置方式的更多代码。
这是android 2浏览器问题。 它缓存GET,POST和PUT(facepalm)请求。 ID
jQuery.ajaxSetup({
cache: false
});
但这仅影响GET请求。
我的最终解决方案是将随机数添加到网址中
url: function(){ return "rest_entity + $.now(); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.