【发布时间】:2016-08-21 12:30:30
【问题描述】:
我正在开发一个 rails 4 项目,我一直在使用 rails Ajax 方法将数据从控制器传输到 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 文件中,但资产文件中的所有脚本(vanilar、coffee 和 jquery)都可以找到。我已经调试了好几个月了,但我无法解决问题所在。
当我尝试检查表单 chrome 时,我得到 200 响应作为 js,但没有执行,我也尝试了不同的浏览器。
这是新的 cmets 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" %>
控制器方法:
def new
@comment = Comment.new(comment_params)
respond_to do |format|
format.js { render layout: false }
end
end
【问题讨论】:
-
以前工作过?您是否在视图文件 .js 中添加了扩展名。独立打开时的文件内容是什么?
-
您是否选择了正确的
DOM元素来附加数据? -
@JamesTan 是的,他们都工作正常。现在在所有其他 .js.erb 文件中都发生了这种情况,甚至 js alert 也没有。 uzaif 是的,我很好地选择了 Dom,除了所有类型的 javascript 方法都没有执行。
-
你在link_to中有remote: true,这是故意的吗?
-
是的,这是故意的@JamesTan
标签: jquery ajax ruby-on-rails-4 turbolinks