<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="js/jquery-3.7.0.js"></script>
<script>
$(function () {
var username_flag = false;
var password_flag = false;
//用户输入框失去焦点
$("[name=username]").blur(function () {
//获取输入框的值
var usernameValue = $(this).val();
//判空
if (usernameValue == null || usernameValue == "") {
$("#span1").text("账号不能为空");
} else {
//判长度
if (usernameValue.length < 5) {
$("#span1").text("账号不能少于5位");
} else {
//判断账号的唯一性
$.get("LoginServlet",{"username":usernameValue},function (date) {
console.log(date)
if (date) {
$("#span1").text("√");
$("#span1").css("color","green");
username_flag = true;
} else {
$("#span1").text("此账号已被注册过!请重新输入");
}
},"json");
}
}
});
//密码输入框失去焦点
$("[name=password]").blur(function () {
var passwordValue = $(this).val();
//判空
if (passwordValue == null || passwordValue == "") {
$("#span2").text("密码不能为空");
} else {
//判长度
if (passwordValue.length < 5) {
$("#span2").text("密码不能少于5位");
} else {
//判内容
var rule = /^\d*$/;
if (rule.test(passwordValue)) {
$("#span2").text("密码不能是纯数字");
} else {
$("#span2").text("√");
$("#span2").css("color","green");
password_flag = true;
}
}
}
});
$("form").submit(function(){
if(username_flag && password_flag){
alert("提交成功")
return true;
}else{
alert("数据有误!")
return false;
}
});
});
</script>
</head>
<body>
<form>
用户名:<input type="text" name="username"><span id="span1" style="color: red"></span><br>
密码:<input type="password" name="password"><span id="span2" style="color: red"></span><br>
<input type="submit" value="登录">
</form>
</body>
</html>
package com.etime.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取名字
String username = request.getParameter("username");
boolean flag;
//假设数据库只有admin用户
if ("admin".equals(username)){
//用户已经存在
flag = false;
} else {
//用户不存在
flag = true;
}
PrintWriter writer = response.getWriter();
writer.print(flag);
writer.close();
}
}
文章来源地址https://www.toymoban.com/news/detail-703626.html
文章来源:https://www.toymoban.com/news/detail-703626.html
到了这里,关于注册页面对数据进行校验,Ajax的使用-数据唯一性的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!