简体   繁体   English

Rails 3-在javascript响应中转义部分生成的html

[英]rails 3 - escaping partial's generated html in javascript response

I am trying to do a simple thing where: 我正在尝试做一个简单的事情,其中​​:

_flash.js.erb: _flash.js.erb:

$("#alerts").append("<%=j render :template => "shared/_flash.html.erb" %>");

Note the <%=j... which escapes the javascript. 请注意<%= j ...,它会转义javascript。

_flash.html.erb: _flash.html.erb:

<% flash.each do |key, value| %>
  <div class="alert-message top <%= "#{key}" %> fade in" data-alert="alert">
    <a class="close" href="#">x</a>
    <p><%=j value %></p>
  </div>
<% end %>

When _flash.js.erb is called, however, something like the following is appended: 但是,在调用_flash.js.erb时,将附加以下内容:

$("#alerts").append("  \u003Cdiv class=alert-message top warning fade in data-alert=alert\u003E
    \u003Ca class=close href=#\u003Ex\u003C/a\u003E
    \u003Cp\u003ELooks like you have already linked with Facebook.\u003C/p\u003E
  \u003C/div\u003E
");

Without the javascript escaping, the response is like this: 如果没有转义,则响应如下:

$("#alerts").append("  <div class="alert-message top warning fade in" data-alert="alert">
    <a class="close" href="#">x</a>
    <p>Looks like you have already linked with Facebook.</p>
  </div>
");

In the first response, TOO much stuff is escaped. 在第一个响应中,逃脱了太多的东西。 In the second response, nothing is escaped and the double quotes mess things up. 在第二个响应中,什么也没逃脱,双引号使事情搞砸了。

What is the recommended way in rails 3 to achieve the above in a robust fashion? 在导轨3中以可靠方式实现上述目标的推荐方法是什么?

Use escape_javascript instead; 改用escape_javascript ; you're JSON-escaping it. 您正在对JSON进行转义

You could alias something the same way j is an alias to json_escape ; 您可以使用与jjson_escape的别名相同的方式来别名; it's just a helper. 它只是一个助手。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM