前端之家收集整理的这篇文章主要介绍了
使用ajax验证用户名是否重复,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
ajaxTest.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
输入用户名:<input type="text" />光标移除检查是否重复
<hr />
<div>显示结果</div>
<script type="text/javascript">
document.getElementsByTagName("input")[0].onblur=function()
{
//alert("aaa");
//取得用户输入的用户名
var username=this.value;
//alert(username)
username=encodeURI(username);
var xhr=createXHR();
//准备以get方式发送请求
xhr.onreadystatechange=function()
{
if(xhr.readyState==4)
{
if(xhr.status==200)
{
var msg=xhr.responseText;
var divlele=document.getElementsByTagName("div")[0];
divlele.innerHTML=msg;
}
}
}
xhr.open("GET","servlet/getServlet?time="+new Date().getTime()+"&username="+username);
xhr.send(null);
}
function createXHR()
{
var xhr=null;
try{
xhr=new ActiveXObject("microsoft.xmlhttp");
}
catch(e)
{
try
{
xhr=new XMLHttpRequest();
}
catch(e)
{
window.alert("浏览器不支持");
}
}
return xhr;
}
</script>
</body>
</html>
Servlet控制:
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class getServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
System.out.println("getservlet:doget");
String username = request.getParameter("username");
byte[] buf = username.getBytes("UTF-8");
username = new String(buf,"UTF-8");
String msg = null;
if (username.equals("sa")) {
msg = "<font color='red'>该用户已经存在</font>";
} else {
msg = "<font color='green'>可以注册</font>";
}
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(msg);
}
}
运行:
原文链接:https://www.f2er.com/ajax/161083.html