2012-02-25 91 views
0

我剛剛做出了一個投票系統,該投票系統每次用戶點擊一個帖子的投票按鈕時都會投票較高,同時還有一個跟蹤用戶投票數量的計數器製作。投票按鈕只刷新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>'); 
+0

所以你說的它的工作的一個部分已經?請到目前爲止顯示JavaScript。 – 2012-02-25 03:26:29

+0

@BenLee我在 – Kellogs 2012-02-25 03:34:46

+0

以上添加了爲什麼不創建一個AJAX請求,並將數據元素的JSON數據用於您需要的任何數據點。如果您只想更新兩個不同位置的文本,則無需重新繪製頁面的所有部分。 – 2012-02-25 03:50:56

回答

1

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!'); 
       } 
      )}; 
     }); 
});