日期:2014-05-16  浏览次数:20750 次

使用Ajax实现检查用户名是可用

Ajax一个常用的地方就在于各大网站上注册时,检查用户名是否已经使用,下面我们就来简单的模拟一下这个功能:

先将html代码给出

 

<script type="text/javascript">
	var xmlHttp;
	function check(name)
	{
		if(window.ActiveXObject)
		{
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}else if(window.XMLHttpRequest)
		{
			xmlHttp=new XMLHttpRequest();
		}
		
		if(xmlHttp!=null)
		{
			xmlHttp.open("POST", "LoginServlet", true);
			xmlHttp.onreadystatechange=function()
			{
				if(xmlHttp.readyState==4 && xmlHttp.status==200)
				{
						var txt=xmlHttp.responseText;
						alert(txt);
						if(txt=="OK")
						{
							document.getElementById("hip").innerHTML="可以使用";
						}else
						{
						document.getElementById("hip").innerHTML="不可以使用";
						}
				}
			}
			
			xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
			xmlHttp.send("name="+name);
		}
	}
</script>
  </head>
  
  <body>
   	<input type="text" name="name" id="name"><br>
   	<input type="submit" onclick="check(document.getElementById('name').value)"><br>
   <div id="hip"></div>
  </body>
</html>


给出一个登陆的Servlet

public class LoginServlet extends HttpServlet
{

	
	public void destroy()
	{
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		out.flush();
		out.close();
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String name=request.getParameter("name");
		System.out.println("name===>"+name);
		if(name.equals("gavin"))
		{
			out.print("OK");
		}else
		{
			out.print("NO");
		}
		out.flush();
		out.close();
	}

	public void init() throws ServletException
	{
		// Put your code here
	}

}

上面的代码中,如果在文本框中输入“gavin”,那么用户名可以使用,如果输入其他,则不能使用,非常简单,仅仅为了练习使用Ajax而已