我在Laravel中使用数据表,我想从数据库中删除一行。当我在路由中将其作为get请求时,它曾经工作过,但由于我将其更改为delete请求并将csrf和方法放在表单下,它停止了工作。我收到-Data Not Deleted
错误。发生这种情况的原因是什么?我从索引控制器接收到的按钮:
$button = ' <button type="button" name="edit" id="'.$data->id.'" class="delete btn btn-danger btn-sm"> <i class="fas fa-fw fa-trash"></i> Delete</button>';
点击删除按钮时出现的HTML表单:
<div class="modal fade" id="confirmModal" tabindex="-1" aria-labelledby="ModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form method="post" id="sample_form" class="form-horizontal">
@csrf
@method('DELETE')
<div class="modal-header">
<h5 class="modal-title" id="ModalLabel">Confirmation</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<h4 align="center" style="margin:0;">Are you sure you want to remove this data?</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" name="ok_button" id="ok_button" class="btn btn-danger">OK</button>
</div>
</form>
</div>
</div>
</div>
脚本:
var employee_id;
$(document).on('click', '.delete', function(){
employee_id = $(this).attr('id');
$('#confirmModal').modal('show');
});
$('#ok_button').click(function(){
$.ajax({
url:"/admin/employees/destroy/"+employee_id,
beforeSend:function(){
$('#ok_button').text('Deleting...');
},
success:function(data)
{
setTimeout(function(){
$('#confirmModal').modal('hide');
$('#employee_table').DataTable().ajax.reload();
alert('Data Deleted');
}, 2000);
},
error: function(xhr, status, error) {
setTimeout(function(){
$('#confirmModal').modal('hide');
$('#employee_table').DataTable().ajax.reload();
alert('Data Not Deleted');
}, 2000);
},
})
});
});
路线:
Route::delete('/admin/employees/destroy/{id}', [EmployeeController::class, 'destroy']);
控制器功能:public function destroy($id)
{
$data = Employee::findOrFail($id);
$data->delete();
}
在你的路由你使用的是删除方法,但在ajax调用你没有提到的方法,所以错误是405方法不允许,
尝试在ajax中添加type: delete
。像这样:
$.ajax({
type: 'DELETE',
url:"/admin/employees/destroy/"+employee_id,
为了解决这个问题,我必须将csrf放入meta:
<meta name="csrf-token" content="{{ csrf_token() }}" />
在脚本的开头使用:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>