Like Unlike toggle button with jQuery's AJAX

Like Unlike toggle button with jQuery's AJAX

本文关键字:AJAX jQuery Unlike toggle button with Like      更新时间:2024-03-24

目标:我正在尝试创建一个按钮,允许用户喜欢网站上的帖子(类似于Facebook的做法),这也会增加/减少按钮之外的点赞数量。

问题:除了一种边缘情况外,其他情况都很好。如果用户已经喜欢上了这篇帖子,他可以不喜欢它,但不再喜欢它。类似/不同切换似乎不起作用,浏览器只向服务器发送了一个"不同"请求。如果用户以前从未喜欢过该图像,则"喜欢/不喜欢"切换似乎很好。

我利用帖子的数据属性通过对这些属性进行操作来切换类似/不同请求。我目前通过Laravel框架使用PHP,并使用jQuery进行前端操作。下面是我的代码示例。

收藏夹.js文件

$(function(){
    $('.favorite-button').click(function(){
        var $this=$(this);
        var post_id=$this.data('postId');
        $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
        });

        if($this.data('favoriteId')){
            //decrement the favorite count
            count=$this.siblings('.favorite-count');
            count.html(parseInt(count.html())-1);
            //send ajax request
            var fav_id=$this.data('favoriteId');
            $this.removeData('favoriteId');
            $.ajax({
                url:'/post/'+post_id+'/favorite/'+fav_id,
                type:'DELETE',
                success: function(result){
                    console.log('post was unfavorited');
                },
                error: function(){
                    console.log('error: did not favorite the post.');
                }
            });
        }

        else{
            //update the favorite count
            count=$this.siblings('.favorite-count');
            count.html(parseInt(count.html())+1);
            //send ajax post request
            $.ajax({
                url:'/post/'+post_id+'/favorite',
                type:'POST',
                success: function(result){
                    //update the data attributes
                    $this.data('favoriteId',result['id']);
                    console.log(result);
                    console.log('post was favorited');
                },
                error: function(){
                    console.log('error: did not favorite the post.');
                }
            });
        }
    });
});

HTML文件

<div class="pull-right">
    <span class="marginer">
        @if(Auth::guest() || $post->favorites->where('user_id',Auth::user()->id)->isEmpty())
            <i  data-post-id="{{ $post->id }}" class="fa fa-heart fa-lg favorite-button"></i>
        @else
            <i  data-favorite-id="{{ Auth::user()->favorites()->where('post_id',$post->id)->first()->id }}" data-post-id="{{ $post->id }}" class="fa fa-heart fa-lg favorite-button"></i>
        @endif
        <span class="favorite-count">{{ $post->favorites->count() }}</span>
    </span>
</div>

除了解决我的问题,如果你认为我在这项任务中不符合最佳实践,请发表评论。我想听听你的意见。

与其尝试使用jQuery,不如尽可能简化的"like/interoid/folding/count"操作

  • 避免从刀片模板进行查询,只将数据发送到视图

以下是我如何处理这个问题,而不是让jQuery来完成繁重的

HTML/呈现

    <button  class='likebutton' data-identifier='1' data-state='liked'>Like</button>
<button class='favoritebutton' data-identifier='1' data-state='favorited'>Favorite</button>
<span class='count counts-1'>123</span>

刀片

<button  class='likebutton' data-identifier='{{!! Post->ID !!}' data-state='{{!! /*<something to see if user liked this>*/?'liked':'unliked' !!}'>{{!! <something to see if user liked>?'liked':'unliked' !!}</button>
<button class='favoritebutton' data-identifier='{{!! Post->ID !!}' data-state='{{!! /*<something to see if user liked>*/?'favorited':'notfavorited' !!}'>{{!! <something to see if user liked>?'favorited':'notfavorited' !!}</button>
<span class='count counts-{{!! $Post->ID !!}}'>{!! $Post->totallikes !!}</span>

JS-

$.ajaxSetup({headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}});
function UserLike(_event){
var state = $(_event.target).data('state');
var postID = parseInt($(_event.target).data('identifier'));
console.log('Status => '+$(_event.target).data('state'));
  $.post('/posts/metadata/likes',{
    'postID':postID
  },function(res){
    $(_event.target).data('state',res.state);
    $(_event.target).text(res.text);
    $('.counts-'+postID).text(res.totallikes);
  }).fail(function(){
    /* do something on fail */
  });
}
function UserFavorite(_event){
var postID = parseInt($(_event.target).data('identifier'));
  $.post('/user/metadata/favorites',{
    'postID':postID
  },function(res){
    $(_event.target).data('state',res.state);
    $(_event.target).text(res.text);
  }).fail(function(){
    /* do something on fail */
  });
}
$("body").on('click','.likebutton',function(_event){    UserLike(_event);   });
$("body").on('click','.favoritebutton',function(_event){    UserFavorite(_event);   });

PHP

// Routes
Route::post('/posts/metadata/likes',function(){
    // auth check
    // handle state/likes
    // ex. response
    // response with json {'state':notliked,'text':'<translated string>','postID':1}
});
Route::post('/user/metadata/favorites',function(){
    // auth check
    // handle state/favorites
    // response with json {'state':favorited,'text':'<translated string>,'postID':1}
});

我建议将$this.data('favoriteId');替换为$this.attr("data-favourite-id")。这对我来说很重要。检查一下这个代码笔http://codepen.io/jammer99/pen/PNEMgV

然而,我不知道为什么您的解决方案不起作用

JQuery data('favoriteId')不设置属性data-favourite,它只是一个运行时设置,它变成元素的特性,而不是属性(这不一样)。

Jquery数据因此不能由服务器端代码设置

您可以在.Prop()的jquery文档中阅读更多信息:http://api.jquery.com/prop/

有一个关于差异的解释。编辑:做了一个大胆的句子!