标题说的就是这一切。
.blade.php文件:
@foreach($posts as $post)
<article class="post" data-postid=" {{ $post->id }} ">
<p>{{ $post->body }}</p>
<div class="info">
Posted by {{$post->user->first_name}} on {{ $post->created_at }}
</div>
<div class="interaction">
<a href="#" class="like">Like</a> |
<a href="#" class="like">Dislike</a>
@if(Auth::user() == $post->user)
|
<a href="#" class="edit">Edit</a> |
<a href="{{ route('post.delete', ['post_id' => $post->id]) }}">Delete</a>
@endif
</div>
</article>
@endforeach
在.blade.php文件中JS:
<script>
var token = '{{ csrf_token() }}';
var urlEdit = '{{ route('edit') }}';
var urlLike = '{{ route('like') }}';
</script>
.js文件:
$('.like').on('click', function(event){
event.preventDefault();
postId = event.target.parentNode.parentNode.dataset['postid'];
var isLike = event.target.previousElementSibling == null; //Checks if it's a like or dislike.
$.ajax({
method: 'POST',
url: urlLike,
data: {isLike: isLike, postId: postId, _token: token}
})
.done(function(){
});
});
似乎什么都没有用,这里发生了什么?
答案 0 :(得分:1)
首先,您必须使用csrf添加meta。
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<script>
$('.like').bind('click', function(event) {
event.preventDefault();
postId = event.target.parentNode.parentNode.dataset['postid'];
var isLike = event.target.previousElementSibling == null;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: url,
type: "POST",
data: {isLike: isLike, postId: postId, _token: token},
dataType: "json",
beforeSend: function(){
$('#loading').show();
},
success: function(resp) {
console.log(resp);
}
});
});
</script>