Ruby on rails 在Rails中使用AJAX加载更多注释
我目前正在使用RubyonRails实现一个类似博客的站点。每个“帖子”都有一些评论。目前我只加载了最新的5条评论,但我想实现一个超链接来加载其余的评论。不幸的是,在我目前的实现中,我得到的只是一堆垃圾 之前Ruby on rails 在Rails中使用AJAX加载更多注释,ruby-on-rails,ajax,Ruby On Rails,Ajax,我目前正在使用RubyonRails实现一个类似博客的站点。每个“帖子”都有一些评论。目前我只加载了最新的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 Thi
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>
最后是我的morecomments.js.rjs:
@comments.each do |p|
page.insert_html :bottom, :comments, :partial => p
end
page.hide 'morecomments'
我对Rails非常陌生,我并不知道所有的meta magic Rails都是在后台进行的。任何帮助都会很棒
谢谢大家! 问题在于您的morecomments操作只是返回javascript并将其注入页面底部
当调用响应.js扩展名的操作时,返回javascript。如果您需要创建动态javascript,这很有用,但实际上您并不需要。让该操作返回一个json文件,并在前端使用一些javascript对其进行解释和注入。或者,您可以将它已经返回的内容粘贴到脚本标记中,这样它(应该)就可以工作了 你的问题是你在混淆概念。您可以选择使用
link\u to\u remote
:update选项,或者使用RJS。不是两者都有
当您使用带有:update选项的link\u to\u remote
时,您的视图希望收到一块html,它将替换与提供给:update的id匹配的DOM元素的内部html。在您的例子中,这是comments div
js部分正在呈现rjs模板,因为您没有告诉它做任何其他事情,它正在生成javascript,链接到远程将其视为html使用它替换注释div
您有两种解决方案:
链接到远程和:更新
您的视图没有更改,并且您的rjs文件没有使用。要实现此修复程序,请将控制器中的foramt.js行替换为:
format.js { render :partial => 'comments', :collection => @comments}
链接到远程调用中删除,:update=>“comments”
-1:虽然此解决方案正确诊断javascript问题,但它完全忽略了导致底层Rails问题的简单错误。
format.js { render :partial => 'comments', :collection => @comments}