给你个例子,用得servlet,你可以改改
index.html
第1个ajax例子var xmlHttp;//局部刷新的关键,通过这个对象与服务器连接
//将xmlHttp实例化
function init()
{
try{
xmlHttp= new ActiveXObject('Msxml2.XMLHTTP');
}
catch(e)
{
try{
xmlHttp= new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e)
{
try{
xmlHttp= new XMLHttpRequest();
}catch(e){}
}
}
}
//调用此方法与服务器互动
function ajax(name)
{
init();
if(name.length==0)
{
document.getElementById("divname").innerHTML="必须输入用户名";
document.getElementById("name").focus();
return;
}
var url="ajax?name="+name+"&&date="+Date();//向servlet传递参数
xmlHttp.open("get",url,true);//向servlet传递参数,设置传递模式和url
xmlHttp.onreadystatechange=handleCheckName;//设置回调方法为handleCheckName
xmlHttp.send(null);
}
function handleCheckName()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
if(xmlHttp.responseText=="1") //xmlHttp.responseText为服务器返回的数据
{
document.getElementById("divname").innerHTML="对不起,用户已存在!";
document.getElementById("divname").style.color="black";
}
if(xmlHttp.responseText=="2")
{
document.getElementById("divname").innerHTML="用户名只能是3-10位字母,数字";
document.getElementById("divname").style.color="black";
}
if(xmlHttp.responseText=="3")
{
document.getElementById("divname").innerHTML="恭喜你,用户名可以继续注册!";
document.getElementById("divname").style.color="red";
}
}
}
}
web.xml
ReturnName
ajax.servlet.ReturnName
ReturnName
/ajax
ReturnName.java
package ajax.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 ReturnName extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=request.getParameter("name");
int a=0;
if(name.equals("asdasd")){
a=1;
}else if(!name.matches("[a-zA-Z0-9]{3,10}")){
a=2;
}else{
a=3;
}
response.getWriter().print(a);
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}