gpt4 book ai didi

javascript - Like Unlike 切换按钮与 jQuery 的 AJAX

转载 作者:行者123 更新时间:2023-11-30 09:51:02 24 4
gpt4 key购买 nike

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

问题:除一种极端情况外,一切正常。如果用户已经喜欢该帖子,他可以不喜欢它但不再喜欢它。似乎喜欢/不喜欢切换不起作用,浏览器只是向服务器发送“不喜欢”请求。如果用户以前从未喜欢过该图像,则喜欢/不喜欢切换似乎工作得很好。

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

favorite.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,不如尝试尽可能简化“喜欢/不喜欢/喜欢/计数”的操作

  • 避免从 blade 模板查询,只将数据发送到 View

下面是我将如何解决这个问题而不是让 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>

Blade

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

关于javascript - Like Unlike 切换按钮与 jQuery 的 AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36520322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com