這是我的看法:
<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');
}
如何洗掉文章?在我點擊洗掉和是按鈕后,它停留在同一頁面上并且無法洗掉文章。
uj5u.com熱心網友回復:
按照以下代碼進行更改
在路由檔案中
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,
}
})
}
});
uj5u.com熱心網友回復:
將型別更改為在 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,
}
})
}
});
uj5u.com熱心網友回復:
像這樣修改你的 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/488924.html
