【问题标题】:Rails render JSON using <%= not working as expectedRails 使用 <%= 渲染 JSON 未按预期工作
【发布时间】:2012-04-09 23:06:06
【问题描述】:

我目前正尝试在我的一个控制器中返回多个 JSON 对象。

  @chromosomes = @organism.chromosomes.to_json
  @file_data = current_user.files.to_json
  respond_to do |format|
    format.html
  end

但是,当我这样做时,在前端:

 <%= @chromosomes %>

  <%= @file_data %>

我没有得到 JSON 对象,而是将数据作为字符串获取,其中包含 &quote 等内容。我尝试解析字符串,例如

console.log($.parseJSON("<%= @chromosomes %>"));

但它仍然无法正常工作。是不是因为发回的请求是html的?

谢谢!

【问题讨论】:

  • 你已经编辑了问题,但答案还是一样,见下文...

标签: ruby-on-rails json


【解决方案1】:

您的代码应如下所示,

respond_to do |format|
    format.html index.html.erb
    format.xml  { render :xml => @organism.chromosomes) }
    format.json { render :json => @organism.chromosomes) }
end

【讨论】:

    【解决方案2】:

    你只需要

    render :json => @organism.chromosomes
    

    通过查看您的编辑,我认为您想要的内容如下:

    console.log($.parseJSON("<%= raw @chromosomes %>"));
    

    【讨论】:

    • 谢谢,但是,当我输出它时,我仍然没有在前端得到一个 json 对象。我已经用更多细节更新了这个问题。再次感谢!
    【解决方案3】:

    问题最终在于 Rails 将 json 数据编码为字符串,这是默认设置。解决我使用的问题

     <%= @chromosomes.html_safe %>
    

    在前端。可以在此处找到有关此的更多信息:

    Weird JSON Javascript problem in Rails

    【讨论】:

      【解决方案4】:

      这应该适用于 Rails 2,

      console.log($.parseJSON(<%= @chromosomes.dump %>));
      

      对于 Rails 3,

      console.log($.parseJSON(<%= @chromosomes.dump.html_safe %>));
      

      String#dump 转义字符并使 parseJSON() 工作。请注意,不需要引号。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-01
        • 1970-01-01
        相关资源
        最近更新 更多