【问题标题】:Rails JSON injectionRails JSON 注入
【发布时间】:2010-10-21 07:57:22
【问题描述】:

在 Rails 2.3 中我一直使用

render :json => { :success => true, :data => @foobar}

将 JSON 数据发送到我的前端。在我正在使用的 Rails 3 中

respond_to :json
...
respond_with @foobar

但我缺少的是:我需要 JSON 结构中的“成功”值。在 Rails 3 中将此类数据注入 JSON 响应的正确方法是什么?


嗯,我也试过了,结果出现以下错误:

SyntaxError (app/controllers/properties_controller.rb:13: syntax error, unexpected tASSOC, expecting '}'
respond_with { :success => true, :data => @property }
                          ^
/app/controllers/properties_controller.rb:13: Can't assign to true
respond_with { :success => true, :data => @property }
                                ^
app/controllers/properties_controller.rb:13: syntax error, unexpected tASSOC, expecting tCOLON2 or '[' or '.'
respond_with { :success => true, :data => @property }

【问题讨论】:

    标签: ruby-on-rails json


    【解决方案1】:

    当事情不符合默认值时,您需要回到之前的自定义方式。 respond_with 接受一个块。

    respond_with @foobar do |format|
      format.json { render :json => { :success => true, :data => @foobar} }
    end
    

    【讨论】:

      【解决方案2】:

      您不能使用对象之类的值。您只需在内部添加一些键/值,覆盖 serializable_hash 方法

      但是你可以在respond_with中生成你的哈希

      respond_with { :success => true, :data => @foobar}
      

      【讨论】:

      • Hmhm,我也试过了,但结果出现以下错误:
      猜你喜欢
      • 2011-02-27
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 2013-11-24
      • 2021-07-18
      • 1970-01-01
      • 2018-09-09
      • 1970-01-01
      相关资源
      最近更新 更多