【问题标题】:Loading more comments using AJAX in Rails在 Rails 中使用 AJAX 加载更多评论
【发布时间】:2010-01-28 02:00:18
【问题描述】:

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

之前

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

点击“查看更多cmets”后

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

最后是我的 morecmets.js.rjs:

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

我真的是 Rails 的新手,我真的不知道所有的元魔法 Rails 在后台做什么。任何帮助都会很棒。

谢谢!

【问题讨论】:

    标签: ruby-on-rails ajax


    【解决方案1】:

    您的问题是您混淆了概念。您可以选择使用 link_to_remote 和 :update 选项,或者使用 RJS。两者都不是。

    当您将link_to_remote 与 :update 选项一起使用时,您的视图期望接收一大块 html,它将替换与提供给 :update 的 id 匹配的 DOM 元素的内部 html。在您的情况下,这是 cmets div。

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

    你有两个解决方案:

    1. link_to_remote:update 一起使用

      您的视图没有改变,并且您的 rjs 文件未被使用。要实施此修复,请将控制器中的 foramt.js 行替换为:

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

      在此解决方案中,您的控制器不会改变。您所要做的就是从您的link_to_remote 呼叫中删除, :update =&gt;'comments'

    【讨论】:

      【解决方案2】:

      问题在于您的 morecmets 操作只是返回 javascript 并将其注入页面底部。

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

      【讨论】:

      • -1:虽然此解决方案正确诊断了 javascript 问题,但它完全忽略了导致底层 Rails 问题的简单错误。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多