Rails3 + jQuery:Ajax响应搞砸了
问题描述:
我正在尝试与Rails 3以及我的应用程序的某些Ajaxification相处。因此,当用户写评论时,应该在点击提交按钮后通过Ajax插入评论。Rails3 + jQuery: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文件放置在意见/评论:
$('#article_comments').append('<%= escape_javascript(render(@comment)) %>');
评论partial(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(但写入数据库)。那么,我该如何解决这个问题?感谢您的期待!
答
好的,感谢您的期待,我找到了解决方案。在评论控制器中,我不得不添加下面的hash到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