【问题标题】:Why is my Backbone.js error callback being called even though Rails is supposedly returning a success response?为什么我的 Backbone.js 错误回调被调用,即使 Rails 应该返回成功响应?
【发布时间】:2011-10-06 01:24:21
【问题描述】:

我正在使用 Backbone.js(版本 0.5.3)并且在 saving a model 时遇到了一些成功回调问题。即使模型已成功保存在服务器上,它也没有运行。

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'

编译的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');
  }
});

控制台输出:

in switch_private
private_entry attribute is currently false
XHR finished loading: "http://localhost:3000/entries/235".

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

添加模型和响应参数,使其成为success: (model, response) ->,并没有什么不同。出了什么问题?

编辑: 根据 Trevor Burnham 的建议,我添加了一个错误回调,并且它正在运行。那么,为了让 Backbone 认为保存成功,我应该从 Ruby on Rails 操作返回什么?目前我有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');
  }
});

这是 PUT 请求:

【问题讨论】:

  • 如果你也添加一个error 回调呢?它会被调用吗?
  • 感谢您的建议,我已经编辑了问题。
  • 我编辑了问题标题。不过,您可能希望更好地重写它:/

标签: javascript backbone.js coffeescript


【解决方案1】:

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

首先,如果您在 create 操作中执行此操作,您将永远不知道您的 id 是什么,因此模型稍后将无法更新(您正在这样做,因为“PUT”)。

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

无论如何,你需要在body中返回一些东西。

默认情况下,Rails 脚手架在成功 update 时返回 head :ok。这与 Backbone 无关。要修复它,请改为返回 JSON:

render json: @entity

(其中@entity 是您在操作中的变量)

【讨论】:

    【解决方案2】:

    Backbone 需要来自服务器的 JSON,然后服务器返回一个文本。

    要在客户端解决此问题,请将数据类型设置为 text 而不是 json,并且服务器期望内容类型为 json .

    options.contentType = 'application/json';
    options.dataType = 'text'; 
    

    您的更新代码如下,

    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');
         }, 
         contentType : 'application/json',
         dataType : 'text'
    });
    

    text数据类型保存后不会被Backbone解析。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-23
      • 2012-08-02
      • 2013-11-07
      相关资源
      最近更新 更多