在Rails中使用AJAX加载更多注释

时间:2010-01-28 02:00:19

标签: ruby-on-rails ajax

我目前正在使用Ruby on Rails实现类似博客的网站。每个“帖子”都有一些评论。目前我只有最新的5条评论加载,但我想实现一个加载其余评论的超链接。不幸的是,在我目前的实现中,我得到的只是一堆垃圾吐出来。

之前

Comments

Posted 7 minutes ago 
New

Posted 1 day ago 
Comment 3

Posted 1 day ago 
Comment 2

Posted 1 day ago 
Comment 1

Posted 1 day ago 
This is a new comment

View more comments

点击“查看更多评论”后

Comments

try { Element.insert("comments", { bottom: "
\n
\n Posted 1 day ago\n 
\n Comment 2\n

\n
" }); Element.insert("comments", { bottom: "
\n
\n Posted 1 day ago\n 
\n Comment 3\n

\n
" }); Element.insert("comments", { bottom: "
\n
\n Posted less than a minute ago\n 
\n New\n

\n
" }); Element.hide("morecomments"); } catch (e) { alert('RJS error:\n\n' + e.toString()); alert('Element.insert(\"comments\", { bottom: \"
\\n
\\n Posted 1 day ago\\n 
\\n Comment 2\\n

\\n
\" });\nElement.insert(\"comments\", { bottom: \"
\\n
\\n Posted 1 day ago\\n 
\\n Comment 3\\n

\\n
\" });\nElement.insert(\"comments\", { bottom: \"
\\n
\\n Posted less than a minute ago\\n 
\\n New\\n

\\n
\" });\nElement.hide(\"morecomments\");'); throw e }

帖子的show.html.erb有:

<div id="morecomments">
  <%= link_to_remote "View more comments", :url=>{:action=>'morecomments',:post_id=>@post.id},:update=>'comments' %>
</div>

在我的帖子控制器中我有

def morecomments
  @post = Post.find(params[:post_id])
  @comments = @post.comments.values_at(Range.new(5, @post.comments.size-1))
  respond_to do |format|
    format.html {redirect_to @post.comments}
    format.js
  end
end

最后我的morecomments.js.rjs:

@comments.each do |p|
  page.insert_html :bottom, :comments, :partial => p
end
page.hide 'morecomments'

我是Rails的新手,我并不知道所有的meta魔术轨道都在后台进行。任何帮助都会很棒。

谢谢!

2 个答案:

答案 0 :(得分:4)

你的问题是你在混合概念。您可以选择将link_to_remote与:update选项一起使用,或使用RJS。不是两个。

当您使用{update}选项使用link_to_remote时,您的视图需要接收一大块html,它将替换与提供的id匹配的DOM元素的内部html:update。在您的情况下,这是注释div。

您的格式.js部分正在渲染rjs模板,因为您没有告诉它做任何其他事情并且它正在生成javascript,link_to_remote将其视为html使用它来替换注释div。

您有两种解决方案:

  1. link_to_remote:update

    一起使用

    您的视图不会更改,并且您的rjs文件未使用。要实现此修复,请使用以下命令替换控制器中的foramt.js行:

     format.js { render :partial => 'comments', :collection => @comments}
    
  2. 使用RJS

    在此解决方案中,您的控制器不会更改。您所要做的就是从, :update =>'comments'来电中删除link_to_remote

答案 1 :(得分:-1)

问题在于,您的更多评论操作只是返回javascript并将其注入页面底部。

当您调用响应.js扩展名的操作时,您将返回javascript。如果您需要创建动态javascript,这很有用,但实际上并非如此。让该操作返回一个json文件,并在前端使用一些解释它并注入它的javascript。或者,您可以坚持已经返回脚本标签的内容并且它(应该)可以工作。