结合jQuery验证,随后阿贾克斯发布者 [英] Combining JQuery Validation followed by ajax post

查看:79
本文介绍了结合jQuery验证,随后阿贾克斯发布者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定,这是简单的,但我是新来的JQuery。我使用jQuery插件来验证一个电子邮件地址,这个作品和code是:

I'm sure this is simple but I'm new to JQuery. I am using the JQuery plugin to validate an email address, this works and the code is:

$(document).ready(function () {
    $("#email").click(function () {
        $(this).attr({value: ''});
    });
    $("#subscribe-form").validate();
});

那么,什么我想要做的就是使用Ajax发表后的电子邮件地址,这同样code正常工作而不验证:

What I then want to do is to post the email address using an ajax post, again this code works fine without the validator:

$(document).ready(function () {
    $('#submit').click(function () {
        var email = $('#email').val();
        var data = "email=" + email;
        $.ajax({
            type: "POST",
            url: "subscript.php",
            data: data,
        });
    });
});

我似乎不能够做的是结合他们两个,因此,如果电子邮件是有效的它就会发布。我真的AP preciate如何做到这一点的帮助。

What I don't seem to be able to do is combine them both, so that if the email is valid it will then post. I'd really appreciate help on how to do this.

非常感谢

推荐答案

.validate()可以通过传递一个对象,具有不同的配置选项进行配置。在这种情况下,设置 submitHandler 用回调到您的表单提交code应该做的工作。

.validate() can be configured by passing in an object with various configuration options. In this case, setting the submitHandler with a callback to your form submission code should do the job.

我还清理你的榜样codeA位,在努力向您展示如何编写更地道的jQuery。

I've also cleaned up your example code a bit, in an effort to show you how to write more idiomatic jQuery.

  1. 我用 jQuery.post() < >而不是 jQuery.ajax() 因为 jQuery.ajax()是一个低级别的方法,当你想定制的Ajax请求的行为,很像我们如何自定义的行为,仅用于 .validate()

  1. I've used jQuery.post() instead of jQuery.ajax() since jQuery.ajax() is a low-level method which is only used when you want to customize the behaviour of an AJAX request, much like how we're customizing the behaviour of .validate().

形式的所有输入可ppared通过调用 .serialize张贴$ P $() 。这prepares一个 URL连接codeD 键值字符串如名称=约翰+ Doe的放大器;电子邮件=约翰%40doe.com ,然后它可以作为一个POST数据

All inputs of the form can be prepared for posting by invoking .serialize(). This prepares a URL encoded key-value string like name=John+Doe&email=john%40doe.com, which can then serve as data for a POST.

Example

$(document).ready(function() {
    $('#myForm').validate({
        submitHandler: function(form) {
            $.post('subscript.php', $('#myForm').serialize());
        }
    });
}); 

这篇关于结合jQuery验证,随后阿贾克斯发布者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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