【问题标题】:Rails: Partial Refreshing on button clickRails:单击按钮时部分刷新
【发布时间】:2012-02-25 03:24:32
【问题描述】:

我最近刚刚制作了一个投票系统,每当用户点击帖子的投票按钮时,该系统的投票数就会更高,同时还会有一个计数器来跟踪用户的投票数量。投票按钮仅刷新 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>

Vote_up.Js

$("#<%=@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>');

【问题讨论】:

  • 所以你说它已经为一个部分工作了?请显示到目前为止的 javascript。
  • 为什么不发出 AJAX 请求,并为您需要的任何数据点提取带有数据元素的 JSON 数据。如果您只想更新两个不同位置的文本,则无需重绘页面的整个部分。
  • @Splash-X 很不好意思问,但我对 jQuery 不熟悉,你能从这个开始吗?

标签: ruby-on-rails ajax ruby-on-rails-3 jquery


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    相关资源
    最近更新 更多