目的:私はFacebookのやり方と同様に、ウェブサイト上の投稿を好きにするボタンを作成しようとしています。好きなものはボタンの他にもありますLike jQueryのAJAXを使用したトグルボタンと違い
問題: 1つのエッジの場合を除いてすべてがうまく動作します。ユーザーが既に投稿を好きだった場合、ユーザーはそれを気に入ることはできませんが、もうそれを気に入らないことがあります。それはlike/unlike toggleが機能していないように見え、ブラウザはサーバに「違う」要求を送るだけです。ユーザーがこれまでイメージを好きになったことがない場合、like/unlikeの切り替えはうまくいくようです。
ポストのデータ属性を使用して、これらの属性を操作することによって、類似した/違う要求を切り替えることができます。私は現在、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>
を提出しますコメントをする。あなたの意見を聞きたい。
あなたは望みの結果を得て、再び同じ問題に陥るでしょう。あなたは、AJAXリクエストを送信した後、DOMのアップデートを適切に処理する必要があります。ドキュメントページはブレードエンジンから一度だけレンダリングされ、新しいページをロードし直すか、JSONレスポンスで更新してクライアント側でアップデートします。 – Gntem
あなたは事件を適切に処理しないことを意味しますか?私の仕事とは対照的に、正しいケースが何であるか教えてください。 – alaboudi