我希望在有人点击投票按钮后自动刷新一个div来计算总票数。投票已经登记,但不会令人耳目一新。
我做过类似的事情;
<% @school_reviews.each do |school_review| %>
<div class="widget-box ">
<div class="widget-header widget-header-small padding-16">
<div class="widget-toolbar no-border">
<span class="vbar"></span>
<span class="vbar"></span>
<small class="theme-color"> <%= school_review.created_at.strftime(" %d-%b %Y ") %> </small>
<span class="vbar"></span>
<span class="vbar"></span>
<% if can? :destroy, school_review %>
<%= link_to(school_review, method: :delete, data: { confirm: 'Are you sure?' }, class: 'red') do %>
<i class="icon-trash bigger-130"></i>
<% end %>
<% end %>
<span class="vbar"></span>
</div>
</div>
<div class="widget-body">
<div class="widget-main padding-16">
<%= simple_format(school_review.description) %>
<div class="voting-banner">
<span class="review-votes theme-color">
<span id= <%= "up_votes_count-#{school_review.id}" %>> <%= school_review.get_likes.size %> </span>
<span>
<%= link_to vote_up_path(id: school_review.id), remote: true do %>
<i class="fa fa-thumbs-up theme-color "></i>
<% end %>
</span>
</span>
<span class="review-votes theme-color">
<span id= <%= "down_votes_count-#{school_review.id}" %>> <%= school_review.get_dislikes.size %> </span>
<span>
<%= link_to vote_down_path(id: school_review.id), remote: true do %>
<i class="fa fa-thumbs-down theme-color "></i>
<% end %>
</span>
</span>
</div>
</div>
</div>
</div>
<div class="hr hr-12"></div>
<% end %>
和vote_up.js.erb看起来像这样;
getElementById(<%= "up_votes_count-#{@school_review.id}" %>).html("<%= @school_review.get_likes.size %>");
而vote_down.js.erb看起来像这个
getElementById(<%= "down_votes_count-#{@school_review.id}"%>).html("<%= @school_review.get_dislikes.size %>");
并且控制器操作看起来像这样;
def vote_up
@school_review = SchoolReview.find(params[:id])
@school_review.liked_by current_user
respond_to do |format|
#format.html {redirect_to school_reviews_path}
format.js { }
end
end
def vote_down
@school_review = SchoolReview.find(params[:id])
@school_review.downvote_from current_user
respond_to do |format|
#format.html {redirect_to school_reviews_path}
format.js { }
end
end
在控制台中,我得到了
GET http://0.0.0.0:3000/vote_up [HTTP/1.1 200 OK 290ms]
GET http://0.0.0.0:3000/vote_up [HTTP/1.1 304 Not Modified 86ms]
谢谢
答案 0 :(得分:0)
<强> JQuery的强>
-
您getElementByID
的来电是一个javascript来电和needs to be attached to the document
对象,正如Octopus-Paul
所述,这是您的第一个问题
第二个问题是您在相应的html
上致电objects
。 .html
is a JQuery function; javascript等效为.innerHTML
你最好这样做:
#app/views/controller/action.html.erb
$("<%=j 'up_votes_count-#{@school_review.id}' %>").html("<%=j @school_review.get_likes.size %>");
这使用纯JQuery,它允许您将相应的数据附加到页面