【问题标题】:Rendering HTML partials within JSON ERB Template Correctly在 JSON ERB 模板中正确呈现 HTML 部分
【发布时间】:2016-01-02 09:37:14
【问题描述】:

我一直在努力让以下内容在我的 Rails 4 应用程序中工作;我正在尝试从搜索 API 返回 JSON 响应,该 API 在返回的对象中有一些生成的 HTML:

## Controller code
...
respond_to do |format|
  format.html # index.html.haml
  format.json # index.json.erb
end

## JSON view code
[
  <% @results.each do |result| %>
  {
    "type": "<%= result.type -%>",
    "content": "<%= escape_javascript render partial: "search/#{result.type}", formats: :html, locals: { result: result } %>"
  }<%= ',' unless result == @results.last %>
  <% end %>
]

当我对搜索 URL 执行 JSON 请求时,生成的代码看起来正确转义并在各种在线 JSON 验证器中成功验证,但 jQuery 拒绝触发 getJSON 的回调函数。

如果我删除 content 部分,回调就会正常触发,所以我知道这与部分渲染有关。

非常感谢任何指针。如上所述,我在其他 Stack Overflow 问题中研究了许多建议的解决方案,但没有任何乐趣。

【问题讨论】:

    标签: jquery ruby-on-rails json ruby-on-rails-4


    【解决方案1】:

    我想建议使用原生 to_json 方法来反对手动创建 json:

    <%=raw  @results.map do |result|
              { "type" => result.type,
                "content" => render(partial: "search/#{result.type}", formats: :html, locals: { result: result }) }
        end.to_json %>
    

    【讨论】:

    • 这让我更接近 - 谢谢。它最终就像你上面所说的那样,但没有escape_javascriptraw 在整个街区。
    • 我忘了raw,当然有必要。我还根据您的评论更新了答案,使其完全正确。
    猜你喜欢
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多