以前没有接触过ajax,想用ajax写一个注册验证用户名是否存在。只好从网上查资料,结果网上的很多资料不是有一些问题,就是太麻烦不容易理解。下面给出一个简单的验证用户名的小例子供初学者参考!
jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<script type="text/javascript">
var xmlhttp;
window.onload = function()
{
var btn1 = document.getElementById("btn1");
btn1.οnclick= loadXMLDoc;
}
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//绑定回调函数
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
var f=xmlhttp.responseText;//接收servlet传回的值
if(f=="用户名可以使用"){
window.location="login.jsp";
}
}
}
//取得输入的值
var name = document.getElementById("username").value;
//第一个参数表示post请求,第二个参数表示提交给Test,第三个参数为true,表示异步请求
xmlhttp.open("POST", "Test", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("name="+name);
}
</script>
<body>
<form>
用户名
<input type="text" name="username" id="username" />
<input type="button" value="提交" id="btn1"/>
<div id="myDiv"></div>
</form>
</body>
</html>
sevlet代码(Test.java):
注意:下面的从数据库中得到的用户名,需要自己改写
public class Test extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
UserDao ud=new UserDao();
boolean flag=ud.sel(name);//注意:此处用户名是从数据库中得到的,需要自己改写
System.out.println(name);
if(flag)
{
out.write("用户名已经存在,请更换");
}
else
{
out.write("用户名可以使用");
}
out.flush();
out.close();
}
}
看来还是很简单的!