register.jsp

<body>
<form>A
用户名:<input id="usernameId" type="text" name="username">
</form>
<span id="tipID"></span>
<script type="text/javascript">
document.getElementById("usernameId").οnblur=function(){
//获取input标签的值
var username = this.value;
var ajax = new XMLHttpRequest();
var method = "GET";
var url = "${pageContext.request.contextPath}/AjaxRegisterServlet?username="+username;
ajax.open(method,url);
ajax.send(null);
//-------------------数据已发出
ajax.onreadystatechange = function(){
if(ajax.readyState == 4){
if(ajax.status == 200){
var tip = ajax.responseText;
document.getElementById("tipID").innerHTML = tip;
}
}
}
}
</script>
</body>

AjaxRegisterServlet.java

public class AjaxRegisterServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

//以流的方式将结果响应到ajax异步对象中
response.setContentType("text/html;charset=UTF-8");
String username = request.getParameter("username");
//解决乱码问题
byte[] bytes = username.getBytes("ISO8859-1");
username = new String(bytes,"UTF-8");
String tip = "";
if("杰克".equals(username)){
tip = "用户名已经存在";
}else{
tip = "可以注册";
}
PrintWriter pw = response.getWriter();
pw.write(tip);
pw.flush();
pw.close();
}
}

用ajax验证用户名是否可以注册 GET方式_ajax