堆栈跟踪显示 create.js.erb 正在渲染,但警报("测试")不起作用



我的堆栈跟踪显示Rendered comments/create.js.erb (4.0ms),但是alert('test');没有被执行(它下面的代码也没有)。为什么会这样?

堆栈跟踪

Started POST "/articles/6/comments" for 127.0.0.1 at 2014-05-25 14:45:07 -0400
Processing by CommentsController#create as JS
  Parameters: {"utf8"=>"✓", "comment"=>{"author"=>"six", "body"=>"six"}, "commit"=>"Create Comment", "article_id"=>"6"}
   (0.1ms)  begin transaction
  SQL (1.8ms)  INSERT INTO "comments" ("article_id", "author", "body", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)  [["article_id", 6], ["author", "six"], ["body", "six"], ["created_at", Sun, 25 May 2014 18:45:07 UTC +00:00], ["updated_at", Sun, 25 May 2014 18:45:07 UTC +00:00]]
   (1.7ms)  commit transaction
  Article Load (0.2ms)  SELECT "articles".* FROM "articles" WHERE "articles"."id" = ? LIMIT 1  [["id", "6"]]
  Comment Load (0.3ms)  SELECT "comments".* FROM "comments" WHERE "comments"."article_id" = 6
  Rendered comments/_list_comments.html.erb (2.1ms)
  Rendered comments/create.js.erb (4.0ms)
Completed 200 OK in 22ms (Views: 8.0ms | ActiveRecord: 4.1ms)

_form.html.erb

<%= simple_form_for [@article, @comment], remote: true do |f| %>
    <%= f.input :author, required: false %>
    <%= f.input :body, required: false %>
    <%= f.button :submit %>
<% end %>

comments_controller.rb

class CommentsController < ApplicationController
    def create
        @comment = Comment.new(comment_params)
        @comment.article_id = params[:article_id]
        if @comment.save
            respond_to do |f|
                f.html { redirect_to article_path(@comment.article_id), notice: 'Comment created!' }
                f.js {
                    @article = Article.find(params[:article_id])
                    @comment = @comment
                    @comments = Comment.where(article_id: params[:article_id])
                }
            end
        else
            respond_to do |f|
                f.html { redirect_to article_path(@comment.article_id), warning: 'Unable to create comment.' }
                f.js {
                    @article = Article.find(params[:article_id])
                    @comment = @comment
                    @comments = Comment.where(article_id: params[:article_id])
                }
            end
        end
    end
    private
        def comment_params
            params.require(:comment).permit(:author, :body)
        end
end

create.js.erb

alert('test');
$("#comments_listing").html(<%= j render 'comments/list_comments' %>);

_list_comments.html.erb

<div id="comments_listing">
<% @comments.each do |comment| %>
    <hr />
    <p><small><%= comment.author %></small></p>
    <p><%= comment.body %></p>
<% end %>
</div>

你应该看看浏览器上呈现的是什么。

但是我认为错误在于你应该像这样调用html方法:

$("#comments_listing").html("<%= j render('comments/list_comments') %>");

如果你不添加引号,脚本将失败

最新更新