isHappy.js在无效时允许ajax调用

时间:2012-09-26 20:29:08

标签: jquery ajax codeigniter

我正在抛弃这一点,希望有人可能发现一个错误,因为我现在已经多次这样做了。它工作正常大约十分钟,但后来爆发了。

我有一个codeigniter网站,其中包含一个非常简单的联系表格,包含3个字段。我正在使用isHappy.js验证表单,然后发送到服务器。 isHappy.js应该停止AJAX函数,直到表单已经验证,但这部分没有发生。如果我单击提交按钮而不填写表单,则验证错误会闪烁,但随后会进行ajax调用并提交表单。

继承人Javascript:

 $(function() { 

 $('#contact-form').isHappy({
   fields: {

     '#email': {
       required: true,
       message: 'How can I reach you sans email??'
     },
     '#subject': {
       required: true,
       message: 'Can you give me a clue to what you inquiring about please'
     },
     '#body': {
       required: true,
       message: 'More details please....'
     }
   }
});

 $('#contact-form').bind('submit', function(e) {
                e.preventDefault();
                var query_params = $('#contact-form').serialize();

                $.ajax({
                    type: 'POST',       
                    url: 'http://website.dev:8080/contact/email/ajax',
                    data: query_params,
                    dataType: 'json',

                    success: function(string){
                        $('#contact-form').fadeOut('medium', function() {
                                $('#linkedin').after("<div style=\"clear:both;\" /><div id=\"contact-complete\" stlye=\"width:100%;height:200px;\"><h1>"+string+"</h1></div>").fadeIn('medium');        
                        });                                                             
                    }

                });
    });     
}); 

和HTML:

<form action="http://website.dev:8080/contact/email" method="post" accept-charset="utf-8" id="contact-form">        
<div class="contact-input">
    <input type="text" name="email" id="email" placeholder="Your email" value="" />
</div>
<div class="contact-input">
    <input type="text" name="subject" id="subject" placeholder="Subject" value="" />
</div>
<div class="contact-textarea">
    <textarea rows="10" placeholder="How can I help you?" name="body" id="body"></textarea>
</div>
<input type="submit" value="Send" id="contact-click" />

2 个答案:

答案 0 :(得分:3)

根据happy.js docs,如果验证失败,则会发生两件事:

  1. 该字段将获得unhappy类。
  2. 该字段将在其前面获得<span>,在DOM中的类unhappyMessage以及该字段ID为_unhappy的ID。
  3. 这纯粹是表现性的。在AJAX调用之前,您必须检查表单是否包含unhappy类的任何输入。

    var is_unhappy = false;
    $('#contact-form div :input').each( function(i) {
        if ( $(this).hasClass('unhappy') ) {
            is_unhappy = true;
            return false;
        }
    });
    if(!is_unhappy){
        //do ajax.
    }
    

答案 1 :(得分:0)

没有HTML但是你使用的是什么类型的输入?看起来您正在使用类型为submit的输入标记,您可以将其更改为类型按钮的输入标记并绑定到单击 - 然后您的问题就会消失。