我正在使用Laravel 5.6创建一个网页。我已编码到政策封面的网页。 id
字段是Foreign Key
。这是来自Policies
表。但是,当我运行并单击删除按钮时,记录不会删除,我收到错误消息" Internal server Error
和Error:1 GET http://127.0.0.1:8000/Error 404 (Not Found)
"
policycover.blade.php
<td>
<button type="button" class="btn btn-danger btn-xs delpolicycover" data-id="{{$value->id}}"><i class="fa fa-trash"></i>Delete</button>
</td>
路线
Route::post('/delpolicycoverdata', 'PolicyCoverController@destroy')->name('delpolicycoverdata');
dashboard.blade.php
<script>
$(document).on('click', '.delpolicycover', function()
{
swal(
{
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this imaginary file!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) =>
{
if (willDelete)
{
var deldata = new FormData();
console.log($("#tokenedit").val());
deldata.append('id', $(this).data('id'));
console.log('id', $(this).data('id'));
deldata.append('_token', $("#tokenedit").val());
$.ajax(
{
type: "post",
data: deldata,
cache: false,
processData: false,
contentType: false,
url: "<?php echo url('/delpolicycoverdata') ?>",
success: function(data)
{
swal("Poof! Your imaginary file has been deleted!",
{
icon: "success",
});
$('#brc' + data).remove();
},
error: function(json)
{
console.log(json);
swal("Error!!",
{
icon: "Error",
});
}
});
}
else
{
swal("Your imaginary file is safe!");
}
});
});
$(document).on("click", ".viewpolicycover", function()
{
$('#vieid').val($(this).data('id'));
$('#viname').val($(this).data('name'));
$('#videscr').val($(this).data('descr'));
$('#policyviewmodel').modal('show');
});
</script>
PolicyCoverController.php
public function destroy(Request $request)
{
$policycover = PolicyCover::find($request->id);
$policecover->delete();
return response()->json($request->id);
}
答案 0 :(得分:1)
在使用ajax发布请求时,您需要保护agaistn csrf ,所以首先将此附加到您的html上
<meta name="csrf-token" content="{{ csrf_token() }}">
您还需要正确设置您的网址,尽量避免混合使用php和js。
然后在你的ajax中你可以这样做:
var idToBeDeleted = $(this).data('id');
$.ajax(
{
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "post",
data: [ id: idToBeDeleted ],
url: '/delpolicycoverdata',
success: function(data)
{
swal("Poof! Your imaginary file has been deleted!",
{
icon: "success",
});
$('#brc' + data).remove();
},
error: function(json)
{
console.log(json);
swal("Error!!",
{
icon: "Error",
});
}
});
上阅读有关csrf保护的更多信息
另外我建议在你的控制器上使用findOrFail,这样你的错误就会被laravel的错误处理程序处理:
public function destroy(Request $request)
{
$policycover = PolicyCover::findOrFail($request->id);
$policecover->delete();
return response()->json($request->id);
}