前端页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>ajax异步验证用户名是否存在</title>
<script type="text/javascript" src="../js/jquery-3.5.1.js"></script>
</head>
<body>
<label for="uname">用户名:</label>
<input type="text" name="uanme" id="uname" onkeyup="ajaxName()" />
<span id="remind"></span>
<script type="text/javascript" src="../js/jquery-3.5.1.js"></script>
<script type="text/javascript">
function ajaxName(){
var uname=$("#uname").val();
if(uname===""){
$("#remind").html("用户名不能为空");
}else{
// $.ajax方法实现
$.ajax({
url: "IsUserServlet",//连接地址
type: "get",//提交方法
data: "uname=" + uname,//数据
dataType: "text",//返回数据类型
async: true,//是否未异步
success: function (result) {//成功后调用的方法
$("#remind").html(result);
}
});
}
}
</script>
</body>
</html>
Servlet接收和判断
package com.feng.servlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
public class AjaxVerification extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
// 接收前端输入的用户名
String uname = req.getParameter("uname");
String[] myName={"小杨","吃饭","喝水"};
if(Arrays.asList(myName).contains(uname)){
resp.getWriter().write("用户名已存在");
}else{
resp.getWriter().write("用户名不存在");
}
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
doGet(req, resp);
}
}