我试图按照制作社交网络的教程,当使用Ajax(添加新条目)在数据库中没有行可用时喜欢和不喜欢的功能被破坏。
教程i&# 39; m跟随 - 此视频是他创建控制器的地方:
https://www.youtube.com/watch?v=drM19VKbCgU&list=PL55RiY5tL51oloSGk5XdO2MGjPqc0BxGV&index=20
发展环境:
错误图片:
Error image link
整个周期:
喜欢和不喜欢按钮(视图):
<a href="#" class="like">{{ Auth::user()->likes()->where('post_id', $post->id)->first() ?
Auth::user()->likes()->where('post_id', $post->id)->first()->like == 1 ?
'You like this post':'Like' : 'Like' }}</a> |
<a href="#" class="like">{{ Auth::user()->likes()->where('post_id', $post->id)->first() ?
Auth::user()->likes()->where('post_id', $post->id)->first()->like == 0 ?
'You don\'t like this post':'Dislike' : 'Dislike' }}</a>
<script>
var urlLike = '{{ route('like') }}';
</script>
路线:
Route::post('/like', [
'uses' => 'PostController@postLikePost',
'as' => 'like'
]);
监听器+ Ajax呼叫:
$('.like').on('click', function(event){
event.preventDefault();
postId = event.target.parentNode.parentNode.dataset['postid'];
var isLike = event.target.previousElementSibling == null;
//console.log(postId+' '+isLike);
$.ajax({
method: 'POST',
url: urlLike,
data: {isLike: isLike, postId: postId, _token: token}
})
.done(function(){
console.log(event.target.innerText);
event.target.innerText = isLike ? event.target.innerText == 'Like' ? 'You like this post':'Like' : event.target.innerText == 'Dislike' ? 'You don\'t like this post':'Dislike' ;
if(isLike){
event.target.nextElementSibling.innerText = 'Dislike';
} else{
event.target.nextElementSibling.innerText = 'Like';
}
});
});
控制器:
public function postLikePost(Request $request){
$post_id = $request['postId'];
$is_like = $request['isLike'] === 'true';
$update = false;
$post = Post::find($post_id);
if(!$post){
return null;
}
$user = Auth::user();
$like = $user->likes()->where('post_id', $post_id)->first();
if($like){
$already_like = $like->like;
$update = true;
if($already_like == $is_like){
$like->delete();
return null;
}
}else{
$like->like = $is_like;
$like->post_id = $post_id;
$like->user_id = $user_id;
}
// This is working when the controller is updating but broken when saving
if($update){
$like->update();
} else{
$like->save();
}
return null;
}
P.S:
我是phpstorm和laravel的新手,如果你知道调试/记录/观察变量值的好方法,比如在eclipse中,那将是值得赞赏的。
答案 0 :(得分:1)
从我看到的ajax请求使用的是错误的网址,请求localhost/public/likes
代替localhost/your_project/public/like
$.ajax({
method: 'POST',
url: 'like',
data: {isLike: isLike, postId: postId, _token: token}
})
应该工作......或
<script>
var urlLike = '{{ URL::to('like') }}';
</script>
不确定为什么route()
无法正常工作