Ajax异步处理当用户申请新用户
Ajax异步处理当用户申请新用户时,输完用户名鼠标点击其他地方后就弹出提示该用户名是否注册的方法:
Ajax处理的JS代码:
<script language="javascript">
var xmlHttpReq;
function createXmlHttpRequest() {
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
} else {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function checkUser() {
createXmlHttpRequest();
xmlHttpReq.onreadystatechange = handle;
var username = document.getElementById("username").value;
var test_username = document.getElementById("test_username");
test_username.style.display = "none";
if (username == "") {
test_username.style.display = "block";
alert("username Can not be empty");
} else {
//url是一个跳转地址,把用户名传过去跳到Action层去调用checkUser方法进行验证
var url = "system/login-checkUser?username=" + username + "&time=" + new Date().getTime();
xmlHttpReq.open("get", url, true);
xmlHttpReq.onreadystatechange = handle;
xmlHttpReq.send(null);
}
}
function handle() {
if (xmlHttpReq.readyState == 4) {
if (xmlHttpReq.status == 200) {
var res = xmlHttpReq.responseText;
var result = document.getElementById("test_username");
result.style.display = "";
result.innerHTML = res; //设置提示信息
}
}
}
</script>
JSP页面调用:
<tr>
<td width="104"><div align="right">用户名:${userexist}</div></td>
<td width="201" height="24"><input name="userdto.username" type="text" class="inputcontent" id="username" value="" onblur="checkUser()" size="20" >
<span class="star">*</span></td>
<td width="473"><div id="test_username" style="display:none"><font color="#FF0000">用户名不能为空</font></div></td>
</tr>
Action层验证用户是否存在方法:
/**验证用户名是否存在**/
public void checkUser(){
try {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
PrintWriter pw = response.getWriter();
String username = request.getParameter("username");
if(userManageBiz.checkUser(username)){
pw.println("<font color='red'> 该用户名已经存在,请重新输入!</font><input type='hidden' name='userexist' value='userexist'/>");
}else pw.println("<font color='blue'> 恭喜你,这个用户名可以用!</font>");
} catch (IOException e) {
e.printStackTrace();
}
}