jQuery验证远程选项Flask

0 投票
1 回答
628 浏览
提问于 2025-04-17 19:08

我正在尝试在一个表单中检查新用户输入的邮箱地址是否已经存在。

这是我的HTML代码:

$("#createform").validate({
            errorClass: "errormessage",
            validClass: "success",

        rules: {
            fname: {
                required: true,
                minlength: 2,
                string: true,
            },

            lname: {
                required: true,
                minlength: 2,
                string: true,
            },

            email: {
                required: true,
                email: true,
                remote: $.getJSON($SCRIPT_ROOT + "/_check_mail")
            },

            password: {
                required: true,
                minlength: 5,
            },

            confirmpassword: {
                equalTo: "#password"
            }
        }

这是我的Flask方法:

@app.route('/_check_mail')
def check_mail():
    mail = request.args.get('email')
    check = database.check_mail(mail)
    return check

在这里,database.check_mail(mail)会检查邮箱是否已经在数据库中,并返回True或False(以JSON格式)。

当我第一次加载页面时,客户端尝试访问Flask的URL (/_check_mail),这个过程是正常的:

  • 请求的URL:http://0.0.0.0:5000/_check_mail
  • 请求方法:GET 状态
  • 状态码:200 OK

但是,当我输入一个邮箱后,发送请求到服务器时,却得到了404的响应:

  • 请求的URL:http://0.0.0.0:5000/[object%20Object]?email=arnoutaertgeerts%40gmail.com
  • 请求方法:GET
  • 状态码:404 NOT FOUND

所以我觉得在发送邮箱时可能出现了问题?有什么想法吗?

1 个回答

0

问题解决了!我在请求中用了这个:

email: {
    required: true,
    email: true,
    remote: function( request, response ) {
        $.getJSON($SCRIPT_ROOT + "/_check_mail", {
        email: $('#email').val()
        }, response);
}

现在除了显示错误信息之外,其他都正常。当邮箱已经存在时,我按照文档的说明返回了错误信息的字符串,但这个信息没有显示出来。不过我在查看收到的响应时,确实能看到这个信息!

撰写回答