首页 > 解决方案 > 如何从 rails 中的 js.erb 传回 jquery 字符串

问题描述

我在 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 中评论我想添加的任何注释,而通常你可以用/*...*/

我正在考虑remote: true从我正在使用的表单中删除,并在提交和设置为时进行正常的 ajax 调用,dataTypehtml我仍然认为在此导轨已经损坏我的字符串之前。

标签: javascriptjqueryruby-on-rails

解决方案


做一个部分:- _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%>");

推荐阅读