You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel/Ajax中获取同名批量删除按钮的正确点击值?

完整实现Laravel + Ajax + SweetAlert的行删除功能

咱们来把你这个删除功能补全,从前端到后端一步步搞定:

1. 完善前端的Ajax与SweetAlert逻辑

你已经写了弹窗的开头,接下来需要加上确认/取消的回调,并发送Ajax请求到后端。另外要注意Laravel的CSRF令牌验证,还有获取当前点击按钮对应的分组ID:

$('button[name="destroy"]').on('click', function(e) {
    // 阻止按钮默认行为(如果是表单内的按钮)
    e.preventDefault();
    
    // 获取当前要删除的分组ID
    const groupId = $(this).val();
    // 获取当前按钮所在的行(方便删除后移除DOM)
    const $row = $(this).closest('tr');

    swal({
        title: "Are you sure?",
        text: "Once you delete this row, you can not rollback ...",
        icon: "warning",
        buttons: true,
        dangerMode: true,
    })
    .then((willDelete) => {
        if (willDelete) {
            // 发送Ajax请求
            $.ajax({
                url: `/groups/${groupId}`, // 对应后端的删除路由
                type: 'DELETE',
                data: {
                    _token: '{{ csrf_token() }}' // Laravel需要的CSRF令牌
                },
                success: function(response) {
                    // 删除成功后的操作:移除该行 + 提示成功
                    $row.fadeOut(300, function() {
                        $(this).remove();
                    });
                    swal("Poof! Your row has been deleted!", {
                        icon: "success",
                    });
                },
                error: function(xhr) {
                    // 处理错误情况
                    swal("Oops!", "Something went wrong while deleting the row.", "error");
                    console.log(xhr.responseText); // 控制台查看错误详情
                }
            });
        } else {
            swal("Your row is safe!");
        }
    });
});

2. 配置Laravel后端路由

在routes/web.php里添加删除路由(用DELETE方法符合RESTful规范):

Route::delete('/groups/{group}', [GroupController::class, 'destroy'])->name('groups.destroy');

3. 实现控制器的destroy方法

在你的GroupController里编写删除逻辑,返回JSON响应:

public function destroy(Group $group)
{
    try {
        $group->delete();
        return response()->json(['success' => true, 'message' => 'Group deleted successfully']);
    } catch (\Exception $e) {
        return response()->json(['success' => false, 'message' => 'Failed to delete group'], 500);
    }
}

这里用了Laravel的路由模型绑定,会自动根据ID查找对应的Group模型,如果找不到会返回404错误。

一些额外的小提示

  • 如果你的按钮在表单里,记得加上type="button",避免触发表单提交:<button type="button" value="{{$group->id}}" name="destroy">...</button>
  • 可以把CSRF令牌放在页面的meta标签里,然后在Ajax里统一获取,这样更灵活:
    <meta name="csrf-token" content="{{ csrf_token() }}">
    
    然后Ajax里的_token改成$('meta[name="csrf-token"]').attr('content')
  • 为了防止重复点击,可以在弹窗出现后禁用按钮,请求完成后再启用。

内容的提问来源于stack exchange,提问作者Sead Ordagić

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:51:01