【问题标题】:AJAX Form how to display loading gifAJAX表单如何显示加载gif
【发布时间】:2012-06-19 15:26:34
【问题描述】:

我有这个用 jQuery 验证插件编写的 AJAX 提交表单。这一切都很完美,但我注意到人们在脚本完成之前重新提交表单,这导致我们的数据库中出现重复记录。这是我到目前为止的代码:

$(document).ready(function(){
$("#myform").validate({
    debug: false,
    rules: {
        fname: {required: true}, 
        sname: {required: true}, 
        sex: {required: true}, 
    },
    messages: {
        fname: {required: "- Field required."},
        sname: {required: "- Field required."},
        sex: {required: "- Field required."},
    },
    errorPlacement: function(error, element) {
        if ( element.is(":radio") ) {
        error.appendTo('.radioError');
        }
        else {
        error.insertAfter( element );
        }
    },
    submitHandler: function(form) {
        $.post('process_participant.php', $("#myform").serialize(), function(data) {
            $('#results').html(data);
        });
        }
    });
});

谁能向我解释如何扩充此代码以将加载 gif 放入我的结果 div 直到我的脚本完成并且加载 gif 被我的实际结果替换?我认为这会阻止人们双击提交按钮。

【问题讨论】:

    标签: jquery ajax forms validation loading


    【解决方案1】:

    这样的事情就可以解决问题。我还在帖子完成之前禁用了提交按钮,这样您就可以避免重复提交。

    $('#mySubmitButton').prop('disabled',true); // Disable submit button
    $('#myAjaxIndicator').show(); // Show ajax indicator
    
    $.post('process_participant.php', $("#myform").serialize(), function(data) {
       $('#results').html(data);
    })
    .complete(function() { 
       $('#mySubmitButton').prop('disabled',false); // Enable submit button
       $('#myAjaxIndicator').hide(); // Hide ajax indicator
    });
    

    complete 回调在成功或错误的情况下执行,因此您可以启用按钮并在任何情况下隐藏指示器。

    【讨论】:

      【解决方案2】:

      在您的submitHandler 函数中,您可以在处理$.post 调用之前隐藏您的表单,然后在$.post 的回调函数中,重新显示您的表单,并做所有您想做的事情。

      submitHandler: function(form) {
          $("#myform").hide(); // Hide the form
          // Here you can insert a loading pic
          $.post('process_participant.php', $("#myform").serialize(), function(data) {
              // Here you can remove the loading pic
              $("#myform").show(); // Show the form
              $('#results').html(data);
          });
      }
      

      【讨论】:

        【解决方案3】:
        $("#myform").submit(function(){
            $('#results').html('<img src="gifUrl" />');
        });
        

        或者完全是这种情况

        submitHandler: function(form) {
            $('#results').html('<img src="gifUrl" />');
            $.post('process_participant.php', $("#myform").serialize(), function(data) {
                $('#results').html(data);
            });
            }
        

        【讨论】:

        • GIF URL 在这里似乎不起作用。它只是将图像 url 打印到页面,例如images/loading.gif - 语法是什么样的?
        • 这个答案会将文字“gifUrl”放入div中。根本不是正确答案,-1
        • 该死,我实际上是指图像 html 代码。喜欢
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-21
        • 1970-01-01
        • 2012-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多