在 data ajax laravel 10 中使用模态删除

问题描述 投票:0回答:1

第一次点击delete-btn中检索数据('product-id')后,我可以获取$product->id并成功删除。

接下来我点击删除另一个产品。它失败了,我认为它没有从删除 btn 检索数据('product-id')。有谁知道我的问题出在哪里

这是我的js代码

$(function () {
    $("#delete-btn").click(function () {
        var productId = $(this).data('product-id');
        $('#deleteModal').data('product-id', productId);
    });

    $('#deleteModal').on('hidden.bs.modal', function () {
        $(this).removeData('product-id');
        $('#deleteModal').modal('hide');
    });

    $("#deleteModal .delete-btn-modal").click(function () {
        var productId = $('#deleteModal').data('product-id');
        $.ajax({
            url: '/products/' + productId,
            type: 'DELETE',
            dataType: 'json',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function (data) {
                console.log(data.message);

                Swal.fire({
                    icon: 'success',
                    title: 'Success!',
                    text: data.message,
                }).then((result) => {
                    if (result.isConfirmed) {
                        $('.table').load(location.href + ' .table')
                    }
                });
            },
    

        $('#deleteModal').modal('hide');
    });
});

我的索引按钮

 <button id="delete-btn" type="button" class="btn btn-danger delete-btn inline-block" data-toggle="modal" data-target="#deleteModal" data-product-id="{{ $product->id }}">
       Delete
</button>

我的模态

<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteModalLabel">Confirm Delete</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger delete-btn-modal" data-dismiss="modal">Delete</button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
jquery ajax laravel
1个回答
0
投票

您的按钮对于每种产品都有相同的

id
。你应该使用类来代替

<button class="delete-btn" type="button" class="btn btn-danger delete-btn inline-block" data-toggle="modal" data-target="#deleteModal" data-product-id="{{ $product->id }}">
           Delete
</button>
© www.soinside.com 2019 - 2024. All rights reserved.