我有一个文章
循环,每篇文章都有一条评论
。
目标是使用 JS 动态/异步地呈现一条评论
。
我的问题是:
如何调用/激活下面定义的逻辑?
#welcome/index.haml
- @articles.each do |article|
= article.title
- article.comments.each do |comment|
%comment-content{ :id => "comment-#{comment.id}" }
#welcome/comment.js.erb
// var
var comment = "#comment-<%= params[:comment_id] %>"
// render
$(comment).html("<%=j render 'comment_content' %>")
#welcome/_comment_content.haml
= comment.content
更新:
在尝试解决这个问题时,我认为我应该添加如下内容:
class WelcomeController < ApplicationController
def index
end
def comment
respond_to do |format|
format.js { render 'comment' }
end
end
最佳答案
您可以使用 AJAX,假设您将在 ready
和 page:change
上显示评论以避免 Turbolinks 问题
注意:我会使用 erb,因为我对 haml 感到不舒服。
第 1 步:定义路线
为您的 AJAX 事件创建一条路由,在本例中我们将创建一个 GET。
#This route will call the action get_one_comment of your articles_controller
get 'articles/get_one_comment'
第 2 步:定义 Controller 操作
在您的articles_controller.rb中创建get_one_comment
操作,因此当您的ajax调用该操作时,它会检索正确的信息,从您的Ajax操作中,您将发送文章的id,因此它将作为params[:article_id]
,还要确保该操作与您的 Controller 回调兼容,有时 Controller 中的 before_action
可能会导致问题:
#articles_controller
def get_one_comment
@article = Article.find params[:article_id]
@comment = @article.comments.last
resond_to do |format|
format.js
end
end
您注意到 respond_to
block 了吗?您可以看到此 Controller 操作将以 js.erb 格式或 js.haml (在您的情况下)响应。
第 3 步:修复标记
我们的 Ajax 请求中的想法是循环浏览我们的文章并将文章 id 发送到 Controller 操作,我们还需要设置某种 css 类或 id,我们的响应脚本将在其中放置评论。
#welcome/index.html.erb
<% @articles.each do |article| %>
<div id="article-<%= article.id %>" class="article-block" data-article-id="<%= article.id %>"
<%= article.title %>
<div class="comment-section">
</div>
</div>
第 4 步:添加 Ajax
现在我们需要创建一个 Ajax 请求来异步加载评论,我将使用 CoffeeScript,在 assets/javascripts
文件夹中选择一个文件,假设我们选择 articles。 js.coffee
,因此当页面加载时,我们将循环浏览所有文章并发送 Ajax 请求:
#articles.js.coffee
loadOneComment = ->
$('.article-block').each ->
$article_block = $(@)
$.ajax '/articles/get_one_comment',
type: 'GET'
dataType: 'script'
data: {
article_id: $article_block.data('article-id')
}
error: (jqXHR, textStatus, errorThrown) ->
console.log("AJAX Error: #{textStatus}")
success: (data, textStatus, jqXHR) ->
console.log("Worked OK!")
$(document).ready loadOneComment
$(document).on 'page:change', loadOneComment
第 5 步:使用响应脚本呈现评论。
创建一个响应脚本,在本例中,我们在 Controller 操作中设置我们将在 format.js
中回答,然后我们需要创建一个 get_one_comment.js.erb
文件,它将包含我们的响应脚本。在此脚本中,我们只需将评论适本地放置在页面中即可。
#get_one_comment.js.erb
$('#article-<%= @article.id %> .comment-section').append('j render(@comment)');
以上内容将为页面中的每个文章 div 呈现部分 comments/_comment.html.erb
。
如果它不起作用,请检查你的JavaScript控制台,我没有测试过,所以我可能有打字错误,或者rails控制台,但基本上我给了你实现它的步骤和正确的方法,你可以自定义您的 AJAX,例如在不同的事件中发送请求,如滚动、悬停、单击等...
关于javascript - 如何在 Rails View 中使用 AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35920911/