[英]Rails: Partial Refreshing on button click
最近,我刚刚建立了一个投票系统,该系统在用户每次点击帖子的投票按钮时都有一个更高的投票,同时还有一个跟踪用户投票数量的计数器。 表决按钮仅刷新HTML的那部分,因此不会刷新整个页面,而不会更新表决计数值,但是除非刷新整个页面,否则表决量的计数器不会改变。 我如何才能做到,当单击投票按钮时,两者都只刷新其部分? 只是不确定从哪里开始。 谢谢!
HTML投票
<div class='Counter'>
<span class='CounterNum'><span id='<%= micropost.id%>'><%=micropost.votes_for %></span></span>
<div class='<%=micropost.id %>'>
<a href="/microposts/<%=micropost.id %>/vote_up" data-remote='true' class='CounterButton b2'>
<span id="CounterIcon" class="<%=micropost.id%>"></span>
</a>
</div>
</div>
HTML的投票金额
<li class='fst'><a class='ProfileLikes' href="/"><%=@user.vote_count(:up) %><span class='ProfileStatText'>Likes</span></a></li>
投票
$("#<%=@micropost.id%>").html('<%="#{@micropost.votes_for}"%>');
$(".<%=@micropost.id%>").html('<a href="/microposts/<%=@micropost.id%>/unvote" data-remote="true" class="SquekCounterButton b3 <%=@micropost.id%>"><span id="SquekCounterIcon" class="<%=@micropost.id%>"></span></a>');
可以在此处查看有关AJAX请求的jQuery API指南: http : //api.jquery.com/jQuery.ajax/
那里有很多信息,所以我会给您一些代码来帮助您入门:
$(document).ready(function(){
$('a.CounterButton').click(function(event){
event.preventDefault(); //This will prevent the link from navigating
$.ajax({
url: $(this).attr('href'), //This pulls the URL from the HREF of the link
dataType: 'json', //This tells the AJAX request we're expecting JSON
success: function(response){
console.log(response); //Output the response to console
//Maybe something like:
$('#' + response.ID ).text(response.Likes);
},
error: function(jqXHR, textStatus, errorThrown){
alert('An error occured!');
}
)};
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.