Rails 4 Ajax 调用只工作一次
Rails 4 Ajax call only works once
我有一个应用程序,您可以在其中发布Links
。每个Link
has_many 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 %>
有没有简单的方法可以解决这个问题?如果您需要额外的详细信息,请告诉我。
这里的问题是有很多div 的 id comment-votes
.当你尝试通过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 } %>")
相关文章:
- Jquery FadeIn FadeOut 只工作一次
- jQuery滚动功能只工作一次
- iOS鼠标中心绑定只工作一次
- mongoose.js Model.remove在循环中只能工作一次
- 复选框一次选中一个不在gridview中工作
- Regex拆分-工作一次
- EventListener只能工作一次
- jQuery animate只在单击时工作一次
- data th JS每页只工作一次
- Jquery选择选项并获取只工作一次的更改值(页面加载时)
- remove仅每隔一次进行儿童工作
- CSS 类在验证时只工作一次
- Chrome扩展程序:浏览器操作单击按钮工作一次
- 单击仅工作一次
- MVC 分部视图中的 JQuery UI 自动完成功能只能工作一次
- Yelp API、OAuth和Angular与JSONP只工作一次
- 为什么这个脚本只工作一次?只替换元素一次,然后再也不替换
- 滚动时加载更多 滚动速度时一次工作两次
- 为什么一个ng应用程序一次工作
- Ajax请求只在每隔一次工作