【问题标题】:AJAX and jQuery validate issueAJAX 和 jQuery 验证问题
【发布时间】:2012-02-27 06:20:57
【问题描述】:

所以我陷入了这个死胡同。我有 AJAX 脚本和 jQuery Validation 插件。使用这个脚本,当我的页面加载空的联系表单时,它会自动提交。如果我在 AJAX 脚本部分上移动或添加 $('#submit').click(function () {,就在 $(document).ready(function() { 下方,那么在提交时它会忽略我的验证表单。

任何帮助将不胜感激。

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type='text/javascript' src='http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js'></script>
<script>
    var captcha_a = Math.ceil(Math.random() * 10);
    var captcha_b = Math.ceil(Math.random() * 10);
    var captcha_c = captcha_a + captcha_b;

    function generate_captcha(id){
        var id = (id) ? id : 'lcaptcha';
        $("#"+id).html(captcha_a + " + " + captcha_b + " = ");
    }

    $(document).ready(function() {

        $('#submit').click(function () {

            jQuery.validator.addMethod("math",
                function(value, element, params) { return this.optional(element) || value == params[0] + params[1]; },
                jQuery.format("Please enter the correct value for {0} + {1}")
            );

            $("#commentform").validate({
                rules: {
                    captcha: {
                        math: [captcha_a, captcha_b]
                    }
                }
            });

        });

    })
</script>

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

        var name = $('input[name=name]');
        var phone = $('input[name=phone]');
        var email = $('input[name=email]');
        var reason = $('select[name=reason]');
        var info = $('textarea[name=info]');

        var data = 'name=' + name.val() + '&phone=' + phone.val() + '&email=' + email.val() +'&reason=' + reason.val() + '&info='  + encodeURIComponent(info.val());

        $('.loading').show();

        $.ajax({
            url: "ajaxformtoemail.php",
            type: "GET",
            data: data, 
            cache: false,
            success: function (html) {  
                if (html==1) {
                    $('.form').fadeOut('slow'); 
                    $('.done').fadeIn('slow');
                } else alert('Sorry, unexpected error. Please try again later.');
            }
         });
         return false;
    });
</script>

【问题讨论】:

  • 为了便于阅读,我对您的代码进行了缩进和格式化。

标签: jquery ajax forms validation contact


【解决方案1】:

您的ajax 正在页面加载时运行,因为没有任何东西可以阻止它。您需要将 ajax 代码放在事件处理程序中,以便仅在您的表单通过验证时调用它。

以下是正确实施验证插件的示例。而且您不需要将validate() 放在点击处理程序中。 Validation 插件内置了一堆自己的处理程序,包括在表单通过验证时触发的submitHandler

<script type='text/javascript'>

$(document).ready(function() {

    jQuery.validator.addMethod("math",
        function(value, element, params) { return this.optional(element) || value == params[0] + params[1]; },
        jQuery.format("Please enter the correct value for {0} + {1}")
    );

    $('form').validate({
        rules {
            // your rules
        },
        submitHandler: function(form) {
            $.ajax({
                // your ajax parameters
            });         
            return false;
        }
    });

});

</script>

Validation Plugin Documentation

一些附带问题...

  1. 如果您使用正确的缩进和标准格式,您的代码将更容易阅读和排除故障。

  2. 不需要使用重复的document.ready 函数。一切都可以在一个里面。

  3. 与 #2 一样,您不需要单独的 &lt;script&gt;&lt;/script&gt; 标签集来包含您的代码。每样东西都可以封装一次。

【讨论】:

  • 非常感谢 Sparky。 Iv 之前使用“stackoverflow”作为参考,但这是我第一次真正寻求帮助。所以,我会通过适当的缩进变得更好。谢谢你的建议,我明天试试。
  • OoMuGaaaash!!!它还活着!!!!我整个周末都在试图解决这个问题。兄弟,你的 Paypal 邮箱是多少,让我给你买杯啤酒。应该在上周五问你,这样我就可以花点时间陪我的女朋友了。谢谢 Sparky,谢谢 'submitHandler: function(form)'
  • @user1234729,我很高兴你明白了。我建议您深入研究插件文档中发布的实时验证示例……它们可能比官方文档更有用,因为官方文档有些难以浏览。
猜你喜欢
  • 2023-03-04
  • 2010-11-22
  • 2011-05-07
  • 2011-12-05
  • 2019-09-30
  • 2011-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多