Laravel技巧集锦(20):使用jq/ajax实现文章点赞/取消点赞

版权声明:http://www.itchuan.net https://blog.csdn.net/sinat_37390744/article/details/88691521

关于点赞业务逻辑实现请参照上一篇文章 Laravel技巧集锦(十):使用关联模型(点赞-文章-用户)

下面重点讲一下用ajax进行无刷新点赞/取消点赞的功能

1、view(用户已经点赞,则显示红心、红字点赞数量;用户未点赞,则显示灰心、灰字点赞数量)

@if($post->zan(\Auth::id())->exists())
   <i  style="font-size: 30px;cursor: pointer; color: red" zan-value="1" 
   zan-id="{{$post->id}}" class="zanbutton glyphicon glyphicon-heart"></i>
@else
   <i   style="font-size: 30px;cursor: pointer; color: grey" zan-value="0" 
   zan-id="{{$post->id}}" class="zanbutton glyphicon glyphicon-heart"></i>
@endif
                                
<span id="zan-count"
   @if($post->zan(\Auth::id())->exists())
        style="font-size: 30px;color: red"
   @else
        style="font-size: 30px; color: grey"
   @endif >

  {{count($post->zans)}}

</span>

2、将点赞按钮绑定click函数,使用ajax请求(点赞操作:灰变红,数量+1;取消点赞:红变红,数量-1)

$('.zanbutton').click(function (event) {
        var target = $(event.target);
        var zan_value = target.attr('zan-value');
        var zan_id = target.attr('zan-id');

        if(zan_value==1){
            $.ajax({
                url:'/posts/' + zan_id + '/unzan',
                method:"POST",
                dataType:"json",
                success:function (data) {

                    if(data.error!=0){
                        alert(data.msg);
                        return;
                    }

                    target.css('color','grey');
                    target.attr('zan-value','0');
                    $('#zan-count').text(parseInt($('#zan-count').text())-1);
                    $('#zan-count').css('color','grey');
                }
            });
        }else{

            $.ajax({
                url:'/posts/' + zan_id + '/zan',
                method:"POST",
                dataType:"json",
                success:function (data) {
                    if(data.error!=0){
                        alert(data.msg);
                        return;
                    }

                    target.css('color','red');
                    target.attr('zan-value','1');
                    $('#zan-count').text(parseInt($('#zan-count').text())+1);
                    $('#zan-count').css('color','red');
                  
                }
            });
        }
    });

猜你喜欢

转载自blog.csdn.net/sinat_37390744/article/details/88691521
今日推荐