标题说明了一切。
.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(){
});
});
- 我已经尝试检查路线是否有问题。
- 我尝试将 token 传递到元标记中,而不是将其定义为 javascript 变量
- 我尝试使用双手镯“而不是单手镯”。
似乎没有任何效果,这是怎么回事?
最佳答案
首先,您必须像这样使用 csrf 添加元数据。
<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>
关于javascript - 使用 Laravel 5 的 Ajax 调用返回错误 500(内部服务器错误),即使传递了 csrf token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40813178/