日期:2014-05-16  浏览次数:20588 次

Ajax 实现 检测用户代码是否存在
<script>
var xmlHttp;
   function createXMLHttpRequest(){
    //表示当前浏览器不是ie,如ns.firefox
    if(window.XMLHTttpRequest){
       xmlHttp = new XMLHttpRequest();
       }else if(window.ActiveXObject){
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
       }
     }

    function validate(field){
        if(trim(field.value).length != 0){
// 创建Ajax核心对象XMLHttpRequest
createXMLHttpRequest();
var url = "user_validate.jsp?userId="+trim(field.value) +"&time"+new Date().getTime();//加time为了使浏览器清空缓存
xmlHttp.open("get",url,true);
// 将方法地址复制费onreadystatechange属性
xmlHttp.onreadystatechange=callback;
//将信息发送到Ajax引擎
xmlHttp.send(null);
}else{
     document.getElementById("spanUserId").innerHTML = "";
}
      }

      function callback(){
        //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);
}
       }
    }

</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 + "]已经存在!");
}
%>