【问题标题】:Bootstrap modal ajax form submited many timesBootstrap modal ajax表单提交多次
【发布时间】:2017-05-07 00:32:30
【问题描述】:

我使用 ajax 在模态中调用表单,并使用模态按钮 .save-modal 使用 ajax 提交表单。表单提交了很多,我不知道为什么?

模态请求的页面-form-中的以下代码:

```

@section('content')
<h1>kk</h1>
<div id="modal">
    {!! Form::model('App\Solution',['url' => $actionPath, 'id' => 'sForm', 'class' => 'form-inline']) !!}

    <div class="form-group">
    {!! Form::label('title', __('Title')) !!}
    {!! Form::text('title',$solution->title,['class' =>'form-control']) !!}
    @php ($eleE =  $errors->first('title'))
     {{-- @include('layouts.form-ele-error') --}}
    </div>
    <div class="form-group">
    {!! Form::label('description', __('Description')) !!}
    {!! Form::textarea('description',$solution->description,['class' =>'form-control']) !!}
    @php ($eleE =  $errors->first('description'))
     {{-- @include('layouts.form-ele-error') --}}
    </div>

    {!! Form::close() !!}


<script>
    $(document).ready(function(){

        $(".save-modal").click(function(e){
            alert('many time alert') //
       e.preventDefault();
       $.ajax({
           url: '{{$actionPath}}'+'/?'+Math.random(),  
           type: "POST",
           data: $("#sForm").serialize(),
           success: function(data){
               $("#modal-body").html($(data).find('#flash-msg'))

               $("#actions-modal").modal('hide')
               //return true;
           },
           error: function(xhr, status, response){
               if ( status == "error" ) {
                    var msg = "Sorry but there was an error: ";

                    // $( "#modal-body" ).html( msg + xhr.status + " " + xhr.statusText );
                    errors = xhr.responseJSON
                    console.log(errors)
                    $("#errors").html('');
                    $.each(errors,function(key, val){

                        console.log(key)
                        $("#errors").append('<span class="has-error help-block">'+val+'</sapn>')

                         //return false;
                    })
                    xhr.responseJSON = null;

                    }
                    return false;
           }
       })
       return false;
      })
      });
      </script>
   </div>
@endsection

$(".save-modal").click(function(e){... 之后的警报被多次警报,特别是在关闭模式并再次打开它并重复尝试保存无效条目时,警报的增加不是固定的,即它是之前尝试的无效数据提交的总和打开模态。

以下是基础页面的模态代码:

$(".action-create").click(function(e){
    e.preventDefault();
    alert($(this).attr('href'))


    mhd = $(this).attr('title');//$(this).text()+' {{__("for Cavity")}}'+' '+$(this).attr('title');
    href = $(this).attr('href')



    //console.log(href)

    $("#actions-modal").on('show.bs.modal', function(){
            $("#modal-hd").html('<h4 style="display: inline">'+mhd+'</h4>');  
            $("#modal-body").html('<h4>{{__('Loading')}}<img src="/imgs/loading.gif" /></h4>')     
            gg(href)
            })

    $("#actions-modal").modal({
        backdrop: 'static',
        keyboard: false        
        });
    });

    $("#actions-modal").on('hidden.bs.modal', function(){

        $("#modal-body").html('');
        $(this).data('bs.modal', null);
        //$(this).children('#errors').html('');
        $("#errors").html('');
        return false;

    });

    gg = function gg(){

        $.ajax({
                type: "GET",
                url: href,
                dataType: 'html',
                success: function(data){
                    //console.log(data)
                    required = $(data).find("#modal");
                    $("#modal-body").html(required);
                },
                error: function(xhr, status, response ){
                    if ( status == "error" ) {
                    var msg = "Sorry but there was an error: ";
                     $( "#modal-body" ).html( msg + xhr.status + " " + xhr.statusText+ " With custom message:<br> "+ xhr.responseText );
                     //console.log(xhr)
                    }
                }

        });
        return false;
    }

我尝试在代码的许多部分添加return false 以减少任何额外的评估,我还尝试将随机数添加到ajax URL Math.random() 但它似乎执行了很多次。

在同一个页面上还有另外一个表单调用是使用modal调用的,有时除了被调用的表单之外还会被保存!

【问题讨论】:

  • @Roamer-1888 否,如果您填写了无效数据,则应在服务器端生成错误422,响应包含字段错误消息。但是,alert 和控制台日志显示,单击Save Changes.save-modal 在关闭模式后会被调用多次,然后再次重新打开它并重新尝试保存无效数据。
  • 因为用户可能忘记提供经过验证的数据。 i,e 将标题字段留空。同样,这似乎不是与错误事件相关的问题,错误显示它只是因为模态保持打开状态

标签: javascript jquery ajax twitter-bootstrap


【解决方案1】:

当您使用 ajax 调用表单时,您应该记住,每次收到响应时都会执行文档就绪的 javascript/jquery 代码。

所以,当你第一次打开你的模型“.save-modal”点击事件是绑定的。关闭并重新打开模型时。再次请求转到浏览器窗口中加载的服务器 ajax 内容,并再次绑定单击事件。这样,您最终将多个匿名函数绑定到单个事件。都将在同一个事件上执行。

解决方案 1(推荐):在单独的 js 文件或包含在主页中的内联中声明函数(不是 ajax)。然后代替使用jQuery绑定点击事件。从“.save-modal”按钮的 onclick 属性调用函数。

解决方案2:声明一个全局变量“IsAjaxExecuting”。测试此变量是否为真,然后从您的保存函数返回(这将停止多次执行)。如果它不是真的,那就让它成为真的。执行你的ajax函数。当收到响应时,再次将其设为假。例如。

var IsAjaxExecuting= false; // new code
$(document).ready(function() {

    $(".save-modal").click(function(e) {
        if(IsAjaxExecuting) return; // new code
        IsAjaxExecuting = true; // new code

        alert('many time alert');
        e.preventDefault();
        $.ajax({
            url: '{{$actionPath}}' + '/?' + Math.random(),
            type: "POST",
            data: $("#sForm").serialize(),
            success: function(data) {
                IsAjaxExecuting = false; // new code
                $("#modal-body").html($(data).find('#flash-msg'))

                $("#actions-modal").modal('hide')
                //return true;
            },
            error: function(xhr, status, response) {
                IsAjaxExecuting = false; // new code
                if (status == "error") {
                    var msg = "Sorry but there was an error: ";

                    // $( "#modal-body" ).html( msg + xhr.status + " " + xhr.statusText );
                    errors = xhr.responseJSON
                    console.log(errors)
                    $("#errors").html('');
                    $.each(errors, function(key, val) {

                        console.log(key)
                        $("#errors").append('<span class="has-error help-block">' + val + '</sapn>')

                        //return false;
                    })
                    xhr.responseJSON = null;

                }
                return false;
            }
        })
        return false;
    })
});

【讨论】:

  • 精彩的解释。
  • 感谢您的赞赏和接受回答。很高兴能提供帮助。
猜你喜欢
  • 2014-05-14
  • 1970-01-01
  • 2017-12-16
  • 2017-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多