简体   繁体   English

Rails escape_javascript和remotipart

[英]Rails escape_javascript and remotipart

When replacing html with jquery and rails (tested on 4.0.4) the following works: 当用jquery和rails替换html(在4.0.4上测试)时,以下工作:

Content of replace.js.erb replace.js.erb的内容

$('#my_div').html("<%= j(render 'my_partial') %>");

Content of _my_partial.html.erb _my_partial.html.erb的内容

"This" works
<%= '"This" also works' %>

However it fails when replace.js.erb is rendered in reponse to a ajax file submit using the remotipart gem (1.2.1) as shown below. 但是当replace.js.erb使用remotipart gem(1.2.1)响应ajax文件提交时,它会失败,如下所示。

Content of create.html.erb create.html.erb的内容

<%= form_for @my_model, :html => {:remote => true} do |f| %>
  <%= f.file_field :some_file %>
  <%= f.submit %>
<% end %>

It causes the following javascript error in the browser because quotes aren't escaped correctly. 它会在浏览器中导致以下javascript错误,因为引号未正确转义。

SyntaxError: Unexpected identifier SyntaxError:意外的标识符

Server response: $('#my_div').html("\\"This\\" works\\n"This" fails\\n"); 服务器响应:$('#my_div')。html(“\\”这个\\“工作\\ n”这个“失败\\ n”);

Note that if I submit without selecting a file the javascript error does not occur and it re-renders correctly. 请注意,如果我在未选择文件的情况下提交,则不会发生javascript错误,并且会重新正确呈现。 It looks like remotipart isn't invoked when a file isn't selected, probably because a multipart form isn't required. 看起来未选择文件时不会调用remotipart,可能是因为不需要多部分表单。

我终于解决了同样的问题:

$("#my_div").html("<%= escape_javascript(render :partial => 'my_partial').gsub('&quot;', "'") %>");

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

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