使用parsley.js进行异步表单提交 [英] Asynchronous form submission with parsley.js

查看:309
本文介绍了使用parsley.js进行异步表单提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个使用Parsley.js进行前端验证并异步提交的表单.表单称为#contactForm,提交按钮为#sendData,当我在空白或无效表单上点击Submit时,就会出现错误.我希望看到来自无效表单数据的错误"警报,但它会继续以其他条件继续运行,并且数据由contactForm.php处理.

I'm trying to create a form that is validated front end using Parsley.js and submitted asynchronously. The form is called #contactForm and the submit button is #sendData, the error comes when I hit submit on an empty or invalid form. I expect to see an 'Error' alert from invalid form data but instead it just continues with the Else condition and the data is processed by contactForm.php.

$(document).ready(function() { 

    // submit data on click and check if valid 
    $('#sendData').click(function(e) { 
        //check if valid with parsley
        var valid = $('#contactForm').parsley ( 'validate' );
        if ( valid === false )
        {
            e.preventDefault();
        }
        else 
        {
            $.post("contactForm.php", $("#contactForm").serialize());       
        }
    });
}); 


下面的正确解决方案.


Proper solution below.

推荐答案

这是您的代码的外观.

$(function() { 
    $('#contactForm').submit(function(e) { 
        e.preventDefault();
        if ( $(this).parsley().isValid() ) {
            $.post("contactForm.php", $(this).serialize());       
        }
    });
}); 

  • 您要捕获表单提交事件,而不是单击提交按钮. (还有其他提交表单的方法,例如按Enter键,不会触发点击,但也必须进行处理.)
  • 您始终希望阻止默认操作.您是通过Ajax提交表单的,因此实际上您永远都不想以传统方式提交表单.
  • 不需要显式地与=== false进行比较. (当表格有效时,Parsley会返回真实值,只需使用该值即可.)
  • $(document).ready(function() { ...$(function() { ....
  • 以一种方式放置大括号. (JS中最常见的约定是非对称",即在开始该语句的一行上是{.)
  • 您的评论是多余的. (他们准确地说出了代码的意思,因此不需要它们.)
    • You want to catch the form submit event, not the click on the submit button. (There are other ways of submitting a form - like pressing Enter - that will not trigger a click but must be handled as well.)
    • You always want to prevent the default action. You submit your form via Ajax, so you actually never want to submit it in the traditional way.
    • There is no need to compare to === false explicitly. (Parsley will return a truthy value when the form is valid, just use that.)
    • $(document).ready(function() { ... is $(function() { ....
    • Settle on one way to place curly braces. (The most common convention in JS is "asymmetric", i.e. { on the one line that started the statement.)
    • Your comments are superfluous. (They say exactly what the code says, so they are not needed.)
    • 在较早版本的parsely(2.x之前)中,使用

      In older versions of parsely (before 2.x), use

      if ( $(this).parsley('validate') ) {
          // ...
      }
      

      这篇关于使用parsley.js进行异步表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆