[英]Rails: js.erb doesn't get executed on client?
I have problem getting the respond script to run on the client. 我在使响应脚本在客户端上运行时遇到问题。 I am quite new to rails, and I am not sure what the remote: true does. 我对Rails很陌生,我不确定遥控器是什么:true。 I have the following link: 我有以下链接:
<%= link_to "#{p.title}", post_path(p), remote: true %>
when I click on it, it directs to the show action which renders post content, and I want to parse the content to a div. 当我单击它时,它会指向显示帖子内容的show操作,并且我想将内容解析为div。 My show.js.erb looks like this 我的show.js.erb看起来像这样
$("#content").html("<h2><%= @post.title %> </h2><p><%= @post.body %></p>");
when I click on the link, I get this responds. 当我点击链接时,我得到这个回应。
Started GET "/posts/14" for 127.0.0.1 at 2014-01-28 10:51:12 -0800
Processing by PostsController#show as JS
Parameters: {"id"=>"14"}
Post Load (0.2ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1 [["id", "14"]]
Rendered posts/show.js.erb (0.2ms)
I do get the whole jquery code looking at the http respond, but somehow it doesn't get executed. 我确实在看http响应时得到了整个jquery代码,但是不知何故它没有被执行。
Use escape_javascript
in show.js.erb
as: 将escape_javascript
中的show.js.erb
用作:
$("#content").html("<h2><%= escape_javascript @post.title %> </h2><p><%= escape_javascript @post.body %></p>");
A cleaner and DRY approach for this would be to move the following: 为此,一种更清洁,更干燥的方法是移动以下内容:
<h2><%= @post.title %> </h2><p><%= @post.body %></p>`
to a partial and render that partial in show.js.erb
. 到部分,并在show.js.erb
渲染该部分。
# _post_detail.html.erb
<h2><%= @post.title %> </h2><p><%= @post.body %></p>
Then in show.js.erb
: 然后在show.js.erb
:
$('#content').html(<%= escape_javascript render("post_detail") %>);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.