我想通过ajax
调用从数据库中删除数据,但是显示错误。
CSRF令牌不匹配
在标题中:
<meta name="csrf-token" content="{{ csrf_token() }}">
在刀片服务器中:
<button class="deletePhoto" data-id="{{ $photo->id }}" data-token="{{ csrf_token() }}">Delete</button>
AJAX呼叫:
$('.deletePhoto').click(function () {
var id = $(this).data('id');
var el = this;
$.ajaxSetup({
headers:{
'X_CSRF_TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/photo/delete/'+id,
type: 'DELETE',
dataType: 'JSON',
data:{
'id': id,
},
success: function () {
$(el).closest(".photo-details").remove();
console.log('DELETED');
},
error: function (xhr) {
console.log(xhr.responseText);
}
})
})
控制器:
public function destroy($id)
{
$photo = Photo::find($id);
$photo->delete();
}
答案 0 :(得分:1)
这是我通常要做的: [AJAX CALL]
$.ajax({
url: '/photo/delete/'+id,
type: 'DELETE',
dataType: 'JSON',
data:{
'id': id,
'_token': '{{ csrf_token() }}',
},
success: function () {
el.closest(".photo-details").remove();
console.log('DELETED');
},
error: function (xhr) {
console.log(xhr.responseText);
}
})
希望我的回答有帮助!
答案 1 :(得分:0)
请在删除ajax methd /中尝试使用此ajax调用csrf令牌。
$('.deletePhoto').click(function () {
var id = $(this).data('id');
var el = this;
$.ajax({
url : '{{ url("photo/delete/") }}/' + id,
type: 'DELETE',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
dataType: 'JSON',
data:{
'id': id,
},
success: function () {
$(el).closest(".photo-details").remove();
console.log('DELETED');
},
error: function (xhr) {
console.log(xhr.responseText);
}
})
})
答案 2 :(得分:0)
输入此json响应
public function destroy($id)
{
$photo = Photo::find($id);
$photo->delete();
return Response::json($photo );
}