如果发生验证错误,则会发送两次Ajax表单

时间:2017-11-09 12:36:41

标签: javascript jquery ajax

我了解event.preventDefault()event.stopImmediatePropagation()。但它对我不起作用。在我的情况下,我有这样的ajax调用:

$('#templateConfirmDialog').on('show.bs.modal', function (event) {
    $(this).find('.modal-yes').click(function(){
                var form = form2js('search_form', '.', true, function (node) {}, false);
                var requestData = JSON.stringify(form, replacer);
                var $formErrors = $('.search_form').find('.alert-danger');
                event.preventDefault();
                event.stopImmediatePropagation();
                $.ajax({
                    type: 'POST',
                    contentType : "application/json",
                    url: '/fraud/template/testCreate',
                    data: requestData,
                    dataType: 'json',
                    success:  function (data) {
                        $formErrors.text('');

                         //if no errors just reload
                        if (data === undefined || data.length === 0) {
                            location.reload();
                        }
                        else {

                            //else bind error messages
                            data.forEach(function(error) {
                                $('#new-' + error.field + '-error').text(error.defaultMessage);
                            })
                        }
                    }
                });
});

我的问题是,当我尝试输入数据时,ajax调用被阻止了很多次。如果我输入一次无效数据 - ajax被调用两次。如果两次--3次。这种行为可能是什么原因?

1 个答案:

答案 0 :(得分:2)

每次发生此事件时:

$('#templateConfirmDialog').on('show.bs.modal', function (event) {

绑定新的单击事件处理程序:

$(this).find('.modal-yes').click(function(){

因此,如果您show.bs.modal两次,那么您有两个click事件处理程序都提交AJAX请求。相反,只需将click事件处理程序绑定到目标可点击元素,而不是每次显示模态时绑定它。

替换它:

$('#templateConfirmDialog').on('show.bs.modal', function (event) {
    $(this).find('.modal-yes').click(function(){
        //...
    });
});

有了这个:

$('#templateConfirmDialog').find('.modal-yes').click(function(){
    //...
});

或者,如果该元素动态添加到DOM,则:

$(document).on('click', '#templateConfirmDialog .modal-yes', function(){
    //...
});

这样,只需在页面加载时创建单击事件处理程序,而不是每次显示模态时都添加新的处理程序。