【问题标题】:How to display a AJAX retrieved HTML code the correct way?如何以正确的方式显示 AJAX 检索到的 HTML 代码?
【发布时间】:2014-05-18 08:37:24
【问题描述】:

我正在使用 Rails 4 和包含的 jQuery 库。当我必须在页面上显示 AJAX 检索到的 HTML 代码时,我遇到了麻烦。也就是说,在我看来,我有以下代码:

# NOTES
#
# In my config/initializers/mime_types.rb file I have
# Mime::Type.register_alias 'text/html', :custom
#
# In my controller action I have:
#
# respond_to do |format|
#   format.custom { render(:partial => 'my_partial', :formats => :html) }
# end

link_to('show comment', comment_path(@comment, :format => :custom), :remote => true, :id => 'css_id')

$('#css_id').on('ajax:success', function(event, xhr, status) {
  $(this).html(xhr)
});

当 AJAX 请求成功时,输出代码如下所示(注意:<b></b> 不是 HTML 解析的):

This is the <b>response html</b>.

通过使用 FireBug,我可以看到响应包含:

<div>This is the &lt;b&gt;response html&lt;/b&gt;.</div>

如何让它以正确的方式显示&lt;b&gt;&lt;/b&gt;?也就是说,我怎样才能使它们被评估为 HTML 代码?

【问题讨论】:

  • 你确定你收到的是纯 HTML 吗?每次我们做这样的事情,我们已经能够在页面上显示 HTML 没有问题 - 也许 HTML 在你发送之前已经被 URI 编码?
  • @Rich Peck - 我更新了问题。

标签: jquery html ruby-on-rails ajax parsing


【解决方案1】:

尝试使用 format.js。示例:

respond_to do |format|
  format.js {
    render partial: "...", layout: false, locals: { ... }
  }
end

【讨论】:

  • 我使用custom 格式并尝试了您的代码,它确实按预期工作:&lt;b&gt;&lt;/b&gt; 未进行 HTML 解析。
  • 我回答了我的问题。
【解决方案2】:

我必须在服务器端运行html_safe 方法,如下所示:

"This is the <b>response html</b>".html_safe

无论如何,谢谢。

【讨论】:

    猜你喜欢
    • 2018-01-04
    • 2015-04-12
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 2011-05-17
    相关资源
    最近更新 更多