欧芹用于验证并通过ajax提交数据

use*_*264 2 forms validation ajax jquery parsley.js

我测试了Parsley框架,我必须说我真的很喜欢实现它的简单性.

我唯一的问题是,如果我尝试附加一个ajax提交,如果表单被正确验证,它似乎似乎没有流行.

下面是我的代码.

<form data-validate="parsley" action="reply.html" method="post" id="main-form">
   <input type="text" name="email" data-type="email" data-required="true" /><br />
  <input type="submit" name="submit" />
</form>


<script>
$("#main-form").submit(function(event){
event.preventDefault();
    $.ajax({
           type: "post",
           url: $(this).attr('action'),
           data: $("#main-form").serialize(), // serializes the form's elements.
            dataType : 'json',
           success: function(data)
           {                
            if(data[0].status == 'success')
                {
                alert('its working ok');
                }
           }
         });
});
/* end simple ajax form post */
</script>
Run Code Online (Sandbox Code Playgroud)

所有它似乎做的,是允许我验证表单,然后正常发布,但是我正在寻找简单的方法来简单验证表单,如果一切都好,请通过ajax提交数据.

我似乎无法通过他们的帮助文档找到一个简单的方法...任何建议非常感谢

Saj*_*ith 5

您可以使用parsely的ajax验证来验证电子邮件.在输入字段中使用data-remote ="http://yoururl.com",该字段将被验证.例如

<input type="text" name="email" data-type="email" data-required="true" data-remote="http://localhost/verify_email.php" />
Run Code Online (Sandbox Code Playgroud)

请注意,我添加了data-remote ="http://localhost/verify_email.php".这将向给定的URL发出ajax请求.

verify_email.php

// Do some code for verifying email id
if($emailIdExist){ 
    echo json_encode(array("error"=>"Sorry, Email exists. Please try with another one"));
}
else{
    echo true;
}
Run Code Online (Sandbox Code Playgroud)