Rails3 + jQuery:Ajax响应搞砸了

时间:2011-05-11 00:05:00

标签: jquery ruby-on-rails ajax

我正在尝试使用jQuery与Rails 3和我的应用程序的一些Ajax化相处。因此,当用户编写注释时,应在按下提交按钮后通过Ajax插入注释。

问题是:Ajax响应包含我的application.haml的整个生成的html。我不知道如何摆脱这个html,只得到在相关的create.js.erb文件中写的预期响应。

这是我的评论控制器:

class CommentsController < ApplicationController

  def new
    @comment = Comment.new
  end

  def create
    @article = Article.find(params[:article_id])
    @comment = current_user.comments.build(params[:comment])
    @comment.article_id = @article.id
    respond_to do |format|
      if @comment.save
        format.html
        format.js

      else
        format.html
        format.js
      end
    end
  end

end

用于评论的表单(在HAML中)如下所示:

  #article_write_comment
    %h2 Write a comment
    #article_write_comment_form
      %p Comments are limited to 1000 chars.
      = form_for([@article, @article.comments.build], :remote => true) do |f|
        .field
          = f.text_area :body, :rows => 10, :cols => 50
        .actions
          = f.submit "Submit"

我的create.js.erb文件放在views / comments中:

$('#article_comments').append('<%= escape_javascript(render(@comment)) %>');

应附加的评论部分(views / comments / _comment.haml)如下所示:

.comment
  = gravatar_for comment.user, :size => 48
  %p
    %b
      = comment.user.name
      said: 
    = time_ago_in_words(comment.created_at)
    ago
  %p
    = simple_format(comment.body)

最后,点击提交后发送的ajax帖子是:

authenticity_token  e2rvcKyjPEx8f31U2vemxCGMfVJzxvqTO+03OCAsNkw=
comment[body]   Test Test Test
commit  Submit
utf8    ✓

但不是这种回应:

$('#article_comments').append('<%= escape_javascript(render(@comment)) %>');

我正在使用网站的html代码获得此类响应: (缩短div的内容以减少分心)

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <div id='content'>
      <div id='header'>
      </div>
      <div id='container'>
        $('#article_comments').append('<div class=\'comment\'>\n  <img alt=\"Alex Gieche\" class=\"gravatar\" src=\"http://gravatar.com/avatar/66d7f7aefd1f45ea810cb3f524cc1780?size=48\" />\n  <p>\n    <b>\n      Alex Gieche\n      said:\n    <\/b>\n    less than a minute\n    ago\n  <\/p>\n  <p>\n    <p>Test Test Test<\/p>\n  <\/p>\n<\/div>\n');
      </div>
      <div id='sidebar'>
      </div>
      <div id='footer'>
      </div>
    </div>
  </body>
</html>

注释未附加到div(但写入数据库)。那么,我该如何解决这个问题呢?谢谢你的期待!

1 个答案:

答案 0 :(得分:0)

好的,谢谢你,我找到了解决方案。在评论控制器中,我不得不将以下哈希添加到format.js以防止在响应中呈现布局:

class CommentsController < ApplicationController

  def new
    @comment = Comment.new
  end

  def create
    @article = Article.find(params[:article_id])
    @comment = current_user.comments.build(params[:comment])
    @comment.article_id = @article.id
    respond_to do |format|
      if @comment.save
        format.html
        format.js {render :layout=>false}
      else
        format.html
        format.js {render :layout=>false}
      end
    end
  end

end