web.php:
Route::delete('/roles/{id}/delete', [RoleController::class, 'delete'])->name('roles.delete');
角色控制器.php:
public function delete($id): string
{
$data = [
'id' => $id
];
return response()->json($data, 200);
}
索引.blade.php:
<a href="{{ route('roles.delete', $role->id) }}" class="btn btn-danger btn-xs btn-action" data-bs-toggle="tooltip" data-bs-custom-class="ls-tooltip" title="{{ __('Delete') }}" data-action-message="{{ __('Delete this role?') }}"><i class="fas fa-trash"></i></a>
<div class="modal fade" id="confirm_action">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header bg-danger">
<h1 class="modal-title fs-5 text-white">{{ __('Please confirm') }}</h1>
</div>
<div class="modal-body">
<div class="modal-message"></div>
<div class="mt-1 d-flex justify-content-end">
<form id="form_delete" method="post">
@csrf
@method('DELETE')
<button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">{{ __('Cancel') }}</button>
<button type="submit" class="btn btn-danger ms-2">{{ __('Delete') }}</button>
</form>
</div>
</div>
</div>
</div>
</div>
应用程序.js:
const confirm_action = document.getElementById('confirm_action');
const btn_action = document.querySelectorAll('.btn-action');
if (typeof(confirm_action) != 'undefined' && confirm_action != null) {
const modal = new bootstrap.Modal(confirm_action);
const form = document.getElementById('form_delete');
let url, id, message;
confirm_action.addEventListener('show.bs.modal', event => {
const confirm_text = confirm_action.querySelector('.modal-message');
confirm_text.textContent = message;
});
form.addEventListener('submit', event => {
event.preventDefault();console.log(url);
axios.delete(url, {
data: {
id: id,
},
}).then(response => {
if (response.status === 200) {
let data = response.data;
console.log(data);
}
}).catch(error => {
console.log(error);
});
});
btn_action.forEach(btn => {
btn.addEventListener('click', event => {
event.preventDefault();
url = btn.getAttribute('href');
id = btn.getAttribute('data-role-id');
message = btn.getAttribute('data-action-message');
modal.show();
});
});
}
我收到以下字符串形式的响应:
HTTP/1.0 200 OK
Cache-Control: no-cache, private
Content-Type: application/json
Date: Sat, 23 Nov 2024 07:07:09 GMT
{"id":"7"}
但是我如何获取数据“id”?
我确信你的
url = undefined
ataxios.delete(url, {
-> axios 会得到url="your web url"
->"your web url"
然后Supported methods: GET, HEAD, POST."
解决方案:
url
在表单中添加隐藏字段单击按钮 => 设置
url
为隐藏字段将表单从 更改
addEventListener
为submit
事件<form id="form_delete" onsubmit="yourSubmitFn()" method="post">
因为当你添加事件监听器 => js 会存储旧的
url
,之后如果你改变 url => js 仍然保留旧url
值你的问题在于你的方法:
该方法的返回类型是
string
,并且根据 php 文档,php 会将类型强制转换为预期的类型;在本例中为string
。通常 Laravel 会使用
Illuminate\Http\Response
类型。我对 Laravel 内部机制了解不够,无法描述为什么它或 Symfony 需要该特定类型的对象才能正确输出您想要的响应。在这种情况下,解决方法当然是从方法中删除类型强制,或将其设置为正确的值。