前端代码
- 松开键盘就会去后台请求一次数据
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/7/14
Time: 13:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX注册</title>
</head>
<body>
<form action="ajax">
<font id="ft" color="aqua" size="15"> 注册页面 </font><br>
<input type="text" name="username" onkeyup="key(this)" placeholder="输入账号"><br>
<!--用来显示提示信息-->
<span id="sp"></span><br>
<input type="password" name="passwd" placeholder="输入密码"><br>
<input type="submit" value="注册">
</form>
<!--使用Jquery-->
<script>
//获取到当前输入框
function key(ipt) {
//获取输入框的value
let value = ipt.value;
//验证value的值
if (value != null && value != null) {
//创建ajax对象
let xmlhttp = new XMLHttpRequest();
//监听状态
xmlhttp.onreadystatechange = function () {
if (xmlhttp.status === 200 && xmlhttp.readyState === 4) {
//获取后端结果
let result = xmlhttp.responseText;
//1 ok 2 no
//获取span标签
let sp = document.getElementById("sp")
if (result == "1") {
//成功 提示绿色
//先清空
sp.innerHTML = "";
//创建标签
let ft = document.createElement("font");
//标签内容
let text = document.createTextNode("正确!可以注册!!!")
//设置自提颜色
ft.setAttribute("color", "green")
//设置字体
ft.appendChild(text);
//将节点插入进span
sp.appendChild(ft);
} else {
//失败 提示红色
sp.innerText = "输入正确的手机号"
sp.style.color = "red";
}
}
}
//设置ajax参数
xmlhttp.open("POST", "ajax?username=" + value)
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoding")
xmlhttp.send("value=" + value)
}
}
</script>
</body>
</html>
servlet代码
- 用来给前端页面响应数据
@WebServlet(name = "ajax", value = "/ajax")
public class HelloServlet extends HttpServlet {
@Override
public void init() {}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
System.out.println("进来servlet了");
//获取name值
String username = request.getParameter("username");
//设置返回给前台的值
String result = null;
//手机号正则表达式
String pattern = "^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$";
if (!Pattern.matches(pattern, username) | username.equals("root") | username.equals("admin")) {
//已有此账号
result = "2";
} else {
//可以注册
result = "1";
}
//response data
response.getWriter().write(result);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
public void destroy() {
}
}
效果图
OK!!!完成啦