如何从rails中的js.erb传回jquery字符串

时间:2018-05-23 03:35:20

标签: javascript jquery ruby-on-rails

我在create.js.erb文件中有这个代码,我希望从我使用remote: true

的子评论表单中找回
<div class="comment">
  <%= @comment.content %>
  <%= link_to "delete", comment_path(@comment, :deletecomment => 
      "delete"), remote: true, method: :delete, data: { confirm: "You 
      sure?" } 
  %>
</div>

看来rails只在这个文件中处理有效的jquery。我只能用html周围的''创建我的代码,使其成为一个jquery字符串,然后像这样发送回来,但是在检查返回的数据时结果很有趣是一个字符串,其中单引号作为字符串的一部分

然后我使用html = data.replace(/\'/g, "");删除单引号,但是有更好的方法吗?

例如我无法在js.erb中评论我想添加的任何注释,通常你可以用/*...*/注释掉js.erb

我正在考虑从我正在使用的表单中删除remote: true并在提交时进行正常的ajax调用并将dataType设置为html,但我认为在此之前还有已经损坏了我的字符串。

1 个答案:

答案 0 :(得分:1)

部分: - _example_partial.html.erb

<div class="comment">
   <%= comment.content %>
   <%= link_to "delete", comment_path(comment, :deletecomment => "delete"),remote: true, method: :delete, data: { confirm: "You sure?" } %>
</div> 

并在create.js.erb

$("#id_of_div_where_the_partial_will_append").append("<%= j render 'example_partial', comment: @comment%>");