Rails:部分刷新按钮点击
问题描述:
我刚刚做出了一个投票系统,该投票系统每次用户点击一个帖子的投票按钮时都会投票较高,同时还有一个跟踪用户投票数量的计数器制作。投票按钮只刷新HTML的那一部分,因此没有整个页面刷新投票计数数字的变化,但投票数量的计数器不会改变,除非整个页面被刷新。我该如何做到这一点,以便在点击投票按钮时只刷新他们的部分?只是不知道从哪里开始。谢谢!Rails:部分刷新按钮点击
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="/"><%[email protected]_count(:up) %><span class='ProfileStatText'>Likes</span></a></li>
Vote_up.Js
$("#<%[email protected]%>").html('<%="#{@micropost.votes_for}"%>');
$(".<%[email protected]%>").html('<a href="/microposts/<%[email protected]%>/unvote" data-remote="true" class="SquekCounterButton b3 <%[email protected]%>"><span id="SquekCounterIcon" class="<%[email protected]%>"></span></a>');
答
jQuery的AP我指导的AJAX请求可以在这里看到: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!');
}
)};
});
});
所以你说的它的工作的一个部分已经?请到目前为止显示JavaScript。 – 2012-02-25 03:26:29
@BenLee我在 – Kellogs 2012-02-25 03:34:46
以上添加了为什么不创建一个AJAX请求,并将数据元素的JSON数据用于您需要的任何数据点。如果您只想更新两个不同位置的文本,则无需重新绘制页面的所有部分。 – 2012-02-25 03:50:56