我正在将ajax发布请求发送到我的发布控制器,但显示500个内部服务器错误
我认为Ajax请求在head标签中带有meta标签。
<script src="{{url('//code.jquery.com/jquery-1.11.1.min.js')}}"></script>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$('.like').on('click', function(event) {
event.preventDefault();
var isLike = event.target.previousElementSibling == null;
console.log(isLike);
$.ajax({
method: 'post',
url: '/liked',
data: {isLiked: isLike, post_id:5}
});
});
});
包含类似Post函数的POst Controller
public function likePost(Request $request)
{
$post_id = $request['post_id'];
$isLike = $request['isLike'] === 'true';
$update = false;
$post = Post::find($post_id);
$user = Auth::user();
$like = $user->like()->where('post_id',$post_id)>first();
if($like)
{
$already_liked = $like->isLiked;
$update = true;
if($already_liked == $isLike)
{
$like->delete();
return null;
}
} else{
$like = new Like();
}
$like->isLiked = $isLike;
$like->user_id = $user->id;
$like->post_id = $post->id;
if($update){
$like->update();
}
else{
$like->save();
}
return null;
}
你能帮我吗
答案 0 :(得分:0)
您可以尝试在
之后使用以下代码
$.ajax({
url:"{{ route('liked') }}", //router in web.php
method:"POST",
data:{query:query},
success:function(data){
//show data to html
}
});
//Laravel router web.php
Route::post('/liked','WebController@store')->name('liked');