一次点击即可多次执行Ajax调用

时间:2016-08-28 07:46:22

标签: jquery ajax

当我点击#deleteCustomerButton时,确认模态显示。如果我确认#delete它运行ajax调用,则从DB中删除客户并从HTML中删除行。

问题是,当我选择删除另一个客户(没有重新加载页面),并确认删除时,它会运行两次ajax调用。如果我选择另一个客户删除,则ajax被称为3次,依此类推。我不知道,它在哪里计算:(

我的HTML表格:

<table class="table table-striped table-bordered table-hover" id="dataTables-customers">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Jméno</th>
                            <th>Adresa</th>
                            <th>Email</th>
                            <th>Telefon</th>
                            <th>Akce</th>
                        </tr>
                    </thead>
                    <tbody>

                        @foreach ($customers as $customer)

                        <tr id="customer{{ $customer->id }}">
                            <td>{{ $customer->id }}</td>
                            <td>{{ $customer->first_name }} {{ $customer->last_name }}</td>
                            <td>{{ $customer->street }}, {{ $customer->zip }}  {{ $customer->city }}</td>
                            <td>{{ $customer->email }}</td>
                            <td>{{ $customer->telephone }}</td>
                            <td>
                                <div class="">
                                    <button class='btn btn-danger btn-xs deleteCustomer deleteCustomer{{$customer->id}}' data-loading-text="Pracuji..." id="deleteCustomerButton" data-id="{{ $customer->id }}" value="{{ $customer->id }}"><span class="fa fa-times"></span> Vymazat</button>
                                    <button class="btn btn-success btn-xs editCustomerButton editCustomerButton{{$customer->id}}" id="editCustomerButton" data-id="{{ $customer->id }}" value="{{ $customer->id }}" data-loading-text="Pracuji...">Upravit</button>
                                </div>
                            </td>
                        </tr>

                        @endforeach

                    </tbody>
                </table>

模态窗口:

<div class="modal fade" id="confirmDeleteCustomerModal" role="dialog" tabindex="-1">
<!-- <div class="modal-dialog"> -->
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true" id="close">&times;</i></button>
            <h4 class="modal-title"> Vymazat zákazníka</h4>
        </div>
        <div class="modal-body">
            Opravdu chcete odstranit zákazníka ze systému?
        </div>
        <div class="modal-footer">
            <button type="button" data-dismiss="modal" class="btn btn-danger delete" id="cancel">Zpět</button>
            <button type="button" data-dismiss="modal" class="btn btn-success" data-loading-text="Pracuji..." id="delete">Odstranit</button>
        </div>
    </div>
</div>

最后我的jQuery函数:

$('#dataTables-customers').on('click', '#deleteCustomerButton', function(){

customerId = $(this).val();
console.log(customerId);
$('.deleteCustomer' + customerId ).button('loading');

$('#confirmDeleteCustomerModal').modal({ backdrop: 'static', keyboard: true }).on('click', '#delete', function (){
    deleteUrl = customerId + '/delete';

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    })

    console.log(deleteUrl);
    $.ajax({
        type: "DELETE",
        url: 'customer/' + customerId + '/delete',
        success: function (data) {
            //console.log(deleteUrl);
            console.log(data);

            $("#customer" + customerId).remove();
            $('.deleteCustomer').button('reset');

            return $.growl.notice({
                message: "Zákazník odebrán ze systému",
                location: "br"
            });
        },
        error: function (data) {
            console.log('Error:', data);
            return $.growl.error({
                message: "Chyba",
                location: "br"
            });
        }
    });
});

$(".modal").on("hidden.bs.modal",function(){
    $('#newCustomerForm').trigger('reset');
    $('.deleteCustomer').button('reset');
});

});

有人可以帮助我摆脱这个麻烦吗?很多。

2 个答案:

答案 0 :(得分:0)

$('#confirmDeleteCustomerModal').modal({ backdrop: 'static', keyboard: true }).on('click', '#delete', function (e){
    e.stopImmediatePropagation(); // or e.stopPropagation();
...
}

你会阻止它冒泡DOM。

答案 1 :(得分:0)

您可以添加Flag例如:DELETING

var DELETING = false; /* Flag declaration */

$('#dataTables-customers').on('click', '#deleteCustomerButton', function(){

customerId = $(this).val();
console.log(customerId);
$('.deleteCustomer' + customerId ).button('loading');

$('#confirmDeleteCustomerModal').modal({ backdrop: 'static', keyboard: true }).on('click', '#delete', function (){
    deleteUrl = customerId + '/delete';

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    })

    console.log(deleteUrl);

    if(!DELETING){ /* checking */
        DELETING = true; /* assign flag to true, so we cannot delete again */
        $.ajax({
            type: "DELETE",
            url: 'customer/' + customerId + '/delete',
            success: function (data) {
                DELETING = false; /* deleted ok, assign flat to false so we can delete again */
                //console.log(deleteUrl);
                console.log(data);

                $("#customer" + customerId).remove();
                $('.deleteCustomer').button('reset');

                return $.growl.notice({
                    message: "Zákazník odebrán ze systému",
                    location: "br"
                });
            },
            error: function (data) {
                DELETING = false; /* error, assign flat to false so we can delete again */
                console.log('Error:', data);
                return $.growl.error({
                    message: "Chyba",
                    location: "br"
                });
            }
        });
    }

});