如何将Laravel自定义变量传入Sweet Alert弹窗提示消息
问题成因
功能不生效、报$user未定义的核心原因有两个:
- HTML规范要求id属性全局唯一,但你在
@foreach循环渲染用户列表时,给每一行的删除按钮、表单都设置了相同的id="btn-submit"、id="delForm",会导致JS选择器只能匹配到第一个元素,后续行的事件绑定、DOM查找都会出现异常。 - Blade的变量输出是服务端渲染逻辑,仅在页面编译阶段执行,且有严格的作用域限制。你写在全局JS代码里的
{!! isset($user) ? json_decode($user->id) : '' !!}不在@foreach循环的作用域内,编译阶段找不到单个循环项的$user变量,自然会触发未定义报错。同时这类服务端输出代码只会在页面首次加载时执行一次,根本无法匹配不同行对应的不同用户数据。
正确实现方案
通过HTML自定义data-*属性传递每行的用户数据,配合类选择器绑定事件即可实现需求,分两步修改:
1. 调整Blade模板代码
移除循环内重复的id属性,改用类选择器绑定事件,同时给删除按钮添加data-username属性存储当前行的用户名,表单不需要设置固定id,通过DOM相对查找即可定位:
<div class="card-body table-responsive p-0"> <table class="table table-hover"> <tbody> <tr> <th>User ID</th> <th>User Name</th> <th>Actions</th> </tr> @if($users->count() != 0) @foreach($users as $user) <tr> <td>{{ $user->id }}</td> <td>{{ $user->name }}</td> @if($user->isSameUser($user->id)) <td class="d-flex"> <div class="btn-group"> <form action="{{ route('admin.users.destroy' , ['user' => $user->id]) }}" method="POST"> @csrf @method('DELETE') <input type="submit" class="btn btn-sm btn-orange ml-1 btn-delete" value="Delete" data-username="{{ $user->name }}" > </form> </div> </td> @endif </tr> @endforeach @else <td colspan="10" class="text-center">Nothing to show!</td> @endif </tbody> </table> </div>
2. 调整JS事件逻辑
将事件绑定目标改为类选择器.btn-delete,点击触发时直接从当前按钮的data-username属性读取对应用户名,拼接进SweetAlert2的提示文本,提交时直接查找当前按钮所属的表单即可,不需要硬编码表单id:
$(document).on('click', '.btn-delete', function(e) { e.preventDefault(); // 定位当前按钮所属的表单 const currentForm = $(this).closest('form'); // 读取当前按钮存储的用户名 const targetUserName = $(this).data('username'); Swal.fire({ title: "Confirmation!", // 修正原代码的拼写错误Confrimation text: `Are you sure you want to delete ${targetUserName} user`, icon: "warning", // SweetAlert2 v2版本用icon参数替代旧版的type参数 allowEscapeKey: false, allowOutsideClick: false, showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes", cancelButtonText: "No", showLoaderOnConfirm: true // 移除旧版废弃的closeOnConfirm配置,v2版本不需要该参数 }).then((result) => { if (result.isConfirmed) { currentForm.submit(); } }); });
补充说明
- 用
data-*属性存储列表行自定义数据是前端处理同类交互的通用方案,不需要把服务端渲染变量直接混写到全局JS中,从根源上避免了作用域不匹配的问题。 - 循环渲染的DOM元素禁止使用重复id,不仅会导致JS逻辑异常,也不符合HTML基础规范。
内容的提问来源于stack exchange,提问作者Pouya Vaghefi
相关产品推荐
相关产品推荐

