这是我自己做的一个’玩具’项目,没有什么实用价值。
用的也是最原始的ajax。
当光标离开输入框实现异步刷新。像后台发出请求并反馈出信息给用户
核心代码:
<h4>登 录 账 号</h4>
<div class="control-group">
<label class="control-label" for="userName">用户名 <sup>*</sup></label>
<div class="controls">
<input type="text" id="input_userName" placeholder="用户名" name="userName" οnblur="validateUserName()"><span id="validateUserName"></span>
</div>
</div>
<script type="text/javascript">
function validateUserName(){
var xmlHttpReq;
var userName = document.getElementById("input_userName").value;
if(window.XMLHttpRequest){
xmlHttpReq = new XMLHttpRequest();
if(xmlHttpReq.overrideMimeType){
xmlHttpReq.overrideMimeType("text/xml");
}
}else if(window.ActiveXObject){
try{
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
}
if(!xmlHttpReq){
window.alter("该浏览器不支持XMLHttpRequest!");
return ;
}
xmlHttpReq.open("post","validateUserName");//设置提交参数
xmlHttpReq.onreadystatechange = function(){
if(xmlHttpReq.readyState == 4){
if(xmlHttpReq.status == 200){
//返回正常
var res = xmlHttpReq.responseText;
//alert(res);
var jsonObject = eval("("+res+")");
//alert(jsonObject.exist);
if(jsonObject.exist){
document.getElementById("validateUserName").innerHTML="<img src=\"themes/images/ico/error.ico\"> 用户名已存在!";
}else {
document.getElementById("validateUserName").innerHTML="<img src=\"themes/images/ico/yes.ico\"> 可以使用";
}
}else{
window.alert("页面请求异常");
}
}
};//指示响应函数
xmlHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpReq.send("userName="+userName); //提交
}
</script>
action:
public String validateUserName() throws IOException {
HttpServletResponse response = ServletActionContext.getResponse();
PrintWriter out = response.getWriter();
boolean temp = false;
temp=new UserInfoDaoImpl().isExistUserInfo(userName);
//JSONObject json2 = new JSONObject();
String json="";
if(temp) {
json="{\"exist\":true}";
//json2.put("exist", true);
}else {
json="{\"exist\":false}";
//json2.put("exist", false);
}
out.println(json);
out.flush();
out.close();
return null;
}