为什么我的Backbone.js错误回调被调用,即使Rails应该返回成功响应?

ben*_*ben 7 javascript coffeescript backbone.js

我正在使用Backbone.js(版本0.5.3)并且在保存模型时遇到成功回调问题.即使模型已成功保存在服务器上,它也不会运行.

CoffeeScript的:

console.log 'in switch_private'
console.log "private_entry attribute is currently #{@model.get('private_entry')}"
@model.save {'private_entry': true},
  success: ->
    console.log 'in success'
Run Code Online (Sandbox Code Playgroud)

编译Javascript:

console.log('in switch_private');
console.log("private_entry attribute is currently " + (this.model.get('private_entry')));
return this.model.save({
  'private_entry': true
}, {
  success: function() {
    return console.log('in success');
  }
});
Run Code Online (Sandbox Code Playgroud)

控制台输出:

in switch_private
private_entry attribute is currently false
XHR finished loading: "http://localhost:3000/entries/235".
Run Code Online (Sandbox Code Playgroud)

head :ok从Ruby on Rails的更新操作返回.

添加模型和响应参数,这样做success: (model, response) ->,并没有什么区别.出了什么问题?

编辑:根据Trevor Burnham的建议,我添加了一个错误回调,它正在运行.那么我应该从Ruby on Rails动作返回什么才能让Backbone认为保存成功呢?目前我有head :ok

编辑2:这是我更新的编译Javascript:

var this_view;
this_view = this;
return this.model.save({
  'private_entry': !(this.model.get('private_entry'))
}, {
  success: function(model, response) {
    return console.log('in success');
  },
    error: function(model, response) {
    return console.log('in error');
  }
});
Run Code Online (Sandbox Code Playgroud)

这是PUT请求:

在此输入图像描述

Bri*_*sio 12

我遇到过这个.您不能只返回head :ok并使用Backbone的默认行为.默认的Backbone.Sync不会有它.

首先,如果你在你的create行动中这样做,你将永远不会知道你的id是什么,所以模型将无法在以后更新(你正在做的,因为"PUT").

其次,在您的update操作中,如果您返回,模型将不知道数据是否真正同步,head :ok因此同步再次失败.但如果你没有,那也没关系id.

无论如何,你需要在体内返回一些东西.

默认情况下,Rails脚手架head :ok成功返回update.这与Backbone没有关系.要修复它,请返回JSON:

render json: @entity
Run Code Online (Sandbox Code Playgroud)

(@entity你的变量在行动中的位置)