dongqie4402 2013-07-13 18:20
浏览 38
已采纳

AJAX和PHP制作像按钮

I have this like button code I want the like number to go up after click but there a need to refresh the page how can I do this:

    <script type="text/javascript">
jQuery(document).ready(function ($) { 
    $('body').on( 'click' , '.votebutton' , function(){
        var span = $(this).children('span');
        var no = parseInt($(this).text(), 10);
        $(span).text(++no);
        var _id = $(this).data('vote');
        $.ajax({
            type: 'POST',
            url: 'vote.php',
            data: { 
                id: _id
            }
        });
    });
});
</script>
<?php 
$q = mysql_query("SELECT * FROM vote");while($row = mysql_fetch_array($q)){
$item[] = $row;
foreach($item as $i){}
  echo "<button class='votebutton' data-vote='".$row[0]."'>Up vote</button><span>".$row[1]."</span>";
}
?>
  • 写回答

2条回答 默认 最新

  • dongwen2162 2013-07-13 18:36
    关注

    It seems like you have two options. You could either A) make the post request return the new like count; or B) increment it manually with jQuery, which would be faster but not necessarily as accurate.

    For the first option, you'd change your AJAX request to something like

    $.ajax({
        ...
    }).done(update_count)
    

    where update_count is a function that takes the request as an argument and updates the count for a button. This method is is slower, but it would show an accurate like count at every instance, since the shown value is always the most current value in the database.

    For the second option, you could select the span for the button and update its value with jQuery. This would be slightly faster, since it wouldn't have to wait for the AJAX query to complete, but it would only increment once, even if somebody else hit the "like" button.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分