我正在开发一个 Rails 4 项目,并且一直在使用 Rails Ajax 方法将数据从 Controller 传输到 js.erb,并且运行良好。我注意到所有 js.erb javascript 都停止工作了一段时间,但从服务器查看文件,请求以 js
形式发送,并且正确呈现。
其中一个回复:
Started GET "/comments/new?comment%5Bcommentable_id%5D=26&comment%5Bcommentable_type%5D=Question" for 127.0.0.1 at 2016-08-21 13:11:32 +0100
Processing by CommentsController#new as JS
Parameters: {"comment"=>{"commentable_id"=>"26", "commentable_type"=>"Question"}}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = 20 ORDER BY "users"."id" ASC LIMIT 1
(0.2ms) BEGIN
SQL (0.3ms) UPDATE "users" SET "last_requested_at" = $1, "updated_at" = $2 WHERE "users"."id" = 20 [["last_requested_at", Sun, 21 Aug 2016 12:11:32 UTC +00:00], ["updated_at", Sun, 21 Aug 2016 12:11:32 UTC +00:00]]
(1.3ms) COMMIT
User Load (1.0ms) Select users.* from users, user_categories where user_categories.user_id = users.id and user_categories.category_id in (select user_categories.category_id from user_categories where user_categories.user_id = 20) and users.id not in (20) and users.id not in (SELECT users.id FROM users INNER JOIN relationships ON users.id = relationships.followed_id and relationships.follower_id = 20) group by users.id limit 5
Rendered comments/_form.html.erb (0.8ms)
Rendered comments/new.js.erb (2.0ms)
Completed 200 OK in 12ms (Views: 3.6ms | ActiveRecord: 3.3ms)
这发生在所有应用程序 js.erb 文件中,但 Assets 文件中的所有脚本(vanilar、coffee 和 jquery)都可以找到。我已经调试了几个月了,但我无法确定出了什么问题。
当我尝试检查 chrome 表单时,我得到 200 作为 js 的响应,但随后没有执行,我也尝试了不同的浏览器。
这里是新评论new.js.erb
<% if @comment.commentable_type == "Question" %>
$('#comment-form').append('<%= escape_javascript render("form") %>');
$('.comment_link').hide();
<% else %>
$('#comment-form_<%= @comment.commentable_id %>').append('<%= escape_javascript render("form") %>');
$('.comment_link').hide();
<% end %>
$('.cancel-comment').click(function() {
$('#new_comment, .comment-form').hide();
$('.comment_link').show();
})
这里是调用触发 Ajax 请求的链接:
<%= link_to " Add a comment", new_comment_path(:comment => { :commentable_type => @question.class.name,
:commentable_id => @question.id}),
:remote => true,
:class => "comment_link",
id:"comment_link" %>
Controller 方法:
def new
@comment = Comment.new(comment_params)
respond_to do |format|
format.js { render layout: false }
end
end
最佳答案
从操作中删除。删除respond_to block 后,您可以在js.erb文件中访问。
respond_to do |format|
format.js { render layout: false }
end
关于jquery - 所有 js.erb 都会运行,但不会在 Rails 4 中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39064208/