1先是在input中添加onblur事件。
<input name="userId" type="text" class="text1" id="userId"size="10" maxlength="10" onkeypress="userIdOnKeyPress()" value="<%=userId %>" onblur="validate(this)">
<span id="spanUserId"></span>
然后编写validate这个函数
共四步:
1、创建XMLHTTPRequest对象
2、调用该对象的open方法,并传入三个参数
3、编写回调函数,来接受服务器的回应
4、所有的准备的编写好后,调用send函数,将信息发送给ajax引擎
function validate(field){
if(trim(field.value).length!=0){
var xmlHttp=null;
//表示当前浏览器不是ie
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
//是ie
}else if(window.ActiveXObject){
xmlHttp=new ActiveXObject("Microsoft.XMLHttP");
}
var url="user_validate.jsp?userId="+trim(field.value)+"&time="+new Date().getTime();//URL为jsp地址,传递一个userId的参数,并加入了时间戳防止浏览器缓存
//设置URLget方式,URL地址,异步请求
xmlHttp.open("get",url,true);
//可以采用匿名函数的方法来会掉
xmlHttp.onreadystatechange=function(){
//ajax引擎状态成功
if(xmlHttp.readyState==4){
//HTTP协议状态为成功
if(xmlHttp.status==200){
if(xmlHttp.responseText!=""){
document.getElementById("sapnUserId").innerHTML="<font color='red'>"+xmlHttp.responseText+"</font>";
}else{
document.getElementById("sapnUserId").innerHTML="";
}
}else{
alert("请求失败"+xmlHttp.status);
}
}
}
//将设置信息发送到ajax引擎
xmlHttp.send(null);
}else{
document.getElementById("sapnUserId").innerHTML="";
}
}
编写user_validate.jsp
这就是服务器端的代码。
String userId=request.getParameter("userId");
if(( UserManager.getInstance().findUserById(userId))!=null){
out.println("用户代码已经存在");
}