Laravel:Ajax使用问题总是返回错误500
再会。 尝试使用 Ajax 发送 GET 方法,总是收到错误 500。使用了 CSRF,但我找不到错误在哪里。这是我的代码:
blade
.....
<meta name="csrf-token" content="{{ csrf_token() }}">
.....
<script>
document.addEventListener("DOMContentLoaded", function() {
let infoModal = document.getElementById('Modal_UserEdit');
infoModal.addEventListener('show.bs.modal', function () {
let userId = document.getElementById("_Input_UserID").value;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ route('settings.user.show') }}",
type: 'GET',
data: { '_token': '{{ csrf_token() }}', id: userId },
success: function(data) {
console.log(data);
}
});
});
});
</script>
web.php
Route::get('settings/users/user/show', [UserController::class, 'show'])->name('settings.user.show');
UserController.php
public function show(Request $request)
{
$form = $request->only(['id']);
$user = DB::table('users')->where('id', $form['id'])->first()->toJson();
return $user;
}
不要认为这是 CSRF 问题,因为:
- 如果在 UserController 内只询问类似 dd($form) 的内容,它会返回
- 如果在 Kernal.php 中禁用 CSRF - 没有任何改变...
有人请帮助理解我做错了什么吗? 谢谢你!
Good day.
Trying to send GET method using Ajax and always getting error 500. CSRF used but I can't find where is error. This is my code:
blade
.....
<meta name="csrf-token" content="{{ csrf_token() }}">
.....
<script>
document.addEventListener("DOMContentLoaded", function() {
let infoModal = document.getElementById('Modal_UserEdit');
infoModal.addEventListener('show.bs.modal', function () {
let userId = document.getElementById("_Input_UserID").value;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ route('settings.user.show') }}",
type: 'GET',
data: { '_token': '{{ csrf_token() }}', id: userId },
success: function(data) {
console.log(data);
}
});
});
});
</script>
web.php
Route::get('settings/users/user/show', [UserController::class, 'show'])->name('settings.user.show');
UserController.php
public function show(Request $request)
{
$form = $request->only(['id']);
$user = DB::table('users')->where('id', $form['id'])->first()->toJson();
return $user;
}
Don't think this is CSRF problem, because:
- If inside UserController just ask something like dd($form) it returns
- If disable CSRF in Kernal.php - nothing changed...
Somebody please help to understand what I'm doing wrong?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
固定的。
感谢日志提醒)))
修复代码:
Fixed.
Thank for log reminder )))
Fixed code: