簡體   English   中英

Rails 4 Ajax調用僅工作一次

[英]Rails 4 Ajax call only works once

我有一個可以在其中發布Links的應用程序。 每個Link都有多條Comments

我設置了ajax,用戶可以在其中投票給特定評論。 當前,用戶可以第一次通過ajax成功地對評論進行增值,但是如果用戶隨后嘗試對同一頁面上的不同評論進行增值,則ajax會中斷,並且值只有在刷新頁面后才會更新。

comments_controller.rb:

def comment_upvote
  @comment = Comment.find(params[:id])
  @link = Link.where(id: @comment.link_id)
  @comment.upvote_by current_user
  respond_to do |format|
    format.html {redirect_to link_path(@link)}
    format.js {}
  end
end  

views / comments / _comment.html.erb:

<div class="well">
  <h2><%= comment.title %></h2>
  <p class="text-muted">Added by <strong><%= comment.author %> <%= comment.author_last_name %></strong> on
  <%= l(comment.created_at, format: '%B, %d %Y %H:%M:%S') %></p>
  <blockquote>
    <p><%= comment.body %></p>
  </blockquote>
  <p><%= link_to 'reply', new_comment_path(parent_id: comment.id, link_id: @link.id)  %></p>

  <%= link_to pointup_comment_path(comment.id), method: :put, remote: true do %>
    +
  <% end %>
  <div id="comment-votes">
    Votes: <%= comment.get_upvotes.size %>
  </div>

視圖/評論/comment_upvote.js.erb:

$('#comment-votes').html("<%= j render "upvotes", locals: { @comment => @comment } %>")

views / comments / _upvotes.html.erb:

Votes: <%= @comment.get_upvotes.size %>

有簡單的方法可以解決此問題嗎? 讓我知道您是否需要其他細節。

這里的問題是,有很多具有id comment-votes div。 當您嘗試通過id獲取元素時,它總是獲得相同的div。

要解決此問題,您需要使每個注釋的id唯一。

views / comments / _comment.html.erb:

<div id="comment-votes-<%= comment.id %>">
  Votes: <%= comment.get_upvotes.size %>
</div>

設置唯一的注釋ID之后。 您只需要更改ajax調用。

視圖/評論/comment_upvote.js.erb:

 $("#comment-votes-<%= @comment.id %>").html("<%= j render "upvotes", locals: { @comment => @comment } %>")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM