[英]Laravel doesn't delete record via ajax
這是我的看法:
<a class="js-ajax-deleteConfirm btn btn-danger rounded-pill mr-2" href="/article/{{$articles->id}}" data-id="{{$articles->id}}">delete</a>
這是我的腳本:
$('.js-ajax-deleteConfirm').click(function () {
let deleteConfirm = confirm('are you sure?');
if (deleteConfirm == true) {
let clickEle = $(this)
let id = clickEle.attr('id');
$.ajax({
url: '/articles/' + id,
type: 'POST',
data: {
"_token": "{{ csrf_token() }}",
'id': id,
'_method': 'DELETE'
}
})
}
});
這是我的路線:
Route::delete('/articles/{id}', 'ArticleController@delete')->name('delete');
Here is my controller:
public function delete($id)
{
$articles = Article::findOrFail($id);
$articles->delete();
return redirect()->route('articles_index')->with('msg_success', 'deleted');
}
如何刪除文章? 在我點擊刪除和是按鈕后,它停留在同一頁面上並且無法刪除文章。
按照以下代碼進行更改
在路由文件中
Route::delete('/articles/{id}', 'ArticleController@delete')->name('articles.delete');
在刀片文件中
<a class="js-ajax-deleteConfirm btn btn-danger rounded-pill mr-2" href="javascript:void(0)" data-id="{{ $articles->id }}" data-url="{{ route('articles.delete', ['id' => $articles->id]) }}">delete</a>
js代碼
$('.js-ajax-deleteConfirm').click(function () {
if(confirm('are you sure?')){
var url = $(this).attr('data-url');
var id = $(this).attr('data-id');
$.ajax({
url: url,
type: 'DELETE',
data: {
"_token": "{{ csrf_token() }}",
'id': id,
}
})
}
});
將類型更改為在 ajax 中刪除,因為您使用的是刪除路由,並且不需要在數據中添加方法。
Route::delete('/articles/{id}', 'ArticleController@delete')->name('delete');
$('.js-ajax-deleteConfirm').click(function () {
let deleteConfirm = confirm('are you sure?');
if (deleteConfirm == true) {
let clickEle = $(this)
let id = clickEle.attr('id');
$.ajax({
url: '/articles/' + id,
type: 'DELETE',
data: {
"_token": "{{ csrf_token() }}",
'id': id,
}
})
}
});
像這樣修改你的 js 代碼,並確保你的 url 是正確的。
$('.js-ajax-deleteConfirm').click(function (e) {
e.preventDefault(); // this will prevent your page to refresh on ajax call
let deleteConfirm = confirm('are you sure?');
if (deleteConfirm == true) {
let clickEle = $(this)
let id = clickEle.attr('id');
$.ajax({
url: '/articles/' + id,
type: 'DELETE', // type should be delete as per your laravel route
data: {
"_token": "{{ csrf_token() }}",
'id': id,
'_method': 'DELETE'
},
success: function() {
window.location.reload();
},
error: function(error) {
alert('Failed to delete');
console.log(error);
}
})
}
});
如果您的 js 代碼在刀片文件中。 您可以像這樣修改您的網址,這將防止您將來出現網址錯誤。
url: "{{URL::to('/articles')}}/" + id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.