Ajax 实现检查用户名重复 (匿名函数实现)
<script language = JavaScript>
function validate(field){
if(trim(field.value).length != 0){
var xmlHttp;
// 创建Ajax核心对象XMLHttpRequest
//表示当前浏览器不是ie,如ns.firefox
if(window.XMLHTttpRequest){
xmlHttp = new XMLHttpRequest();
}else if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "user_validate.jsp?userId="+trim(field.value) +"&time"+new Date().getTime();
xmlHttp.open("get",url,true);
// 将方法地址复制费onreadystatechange属性
xmlHttp.onreadystatechange=function(){
//alert(xmlHttp.readyState);
//Ajax引擎状态为成功
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
if(trim(xmlHttp.responseText) != ""){
document.getElementById("spanUserId").innerHTML = "<font color=red>"+xmlHttp.responseText+"</font>";
}else{
document.getElementById("spanUserId").innerHTML ="";
}
}else{
alert("请求失败,错误代码="+xmlHttp.status);
}
}
};
//将信息发送到Ajax引擎
xmlHttp.send(null);
}else{
document.getElementById("spanUserId").innerHTML = "";
}
}
</script>
<input name="userId" type="text" class="text1" id="userId" size="10" maxlength="10" onkeypress="userIdOnKeyPress()" onblur="validate(this)"/>
<span id="spanUserId"></span>
user_validate.jsp文件实现如下
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ page import="com.bjsxt.drp.sysmgr.*" %>
<%
/*
//可以采用清除缓存的方法,如下
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-store"); //HTTP1.1
response.setHeader("Pragma", "no-cache"); //HTTP1.0
response.setDateHeader("Expires", 0);
*/
String userId = request.getParameter("userId");
if (UserManager.getInstance().findUserById(userId) != null) {
out.println("用户代码[" + userId + "]已经存在!");
}
%>