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

一个存AJax例子
<script type="text/javascript">

var xmlHttpRequest;

function createXMLHttpRequest(){
//表示当前浏览器不是IE,如Maxthon,firefox
if(window.XMLHttpRequest){
   xmlHttpRequest=new XMLHttpRequest();
}else if(window.ActiveXObject){
   xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
}
}
function validate(field){
//alert("Hello!!!");
//document.getElementById("userId").value
//alert(field.value);
if(trim(field.value).length!=0){
     //创建XMLHttpRequest
    createXMLHttpRequest();
    var url="user_validate.jsp?userId="+trim(field.value)+"&timestamp="+new Date().getTime();
    xmlHttpRequest.open("GET",url,true);
    //方法地址处理完成后自动调用,回调
xmlHttpRequest.onreadystatechange=callback;
//将参数发送到Ajax引擎
xmlHttpRequest.send(null);
}else{
document.getElementById("userIdSpan").innerHTML="";
}
}
function callback(){
  if(xmlHttpRequest.readyState==4){//Ajax引擎初始化成功
     if(xmlHttpRequest.status==200){//HTTP协议成功
       //alter(xmlHttpRequest.responseText);
        document.getElementById("userIdSpan").innerHTML="<font color='red'>"+xmlHttpRequest.responseText+"</font>";
     }else{
        alert("请求失败,错误码="+xmlHttpRequest.status);
    
     }
  }
}

</script>

user-validate.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.drp.sysmgr.manager.*" %>
<%
//可以采用清楚缓存的方法,如下
//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("用户代码已经存在!!!");
}else{

    out.println("");
}
%>

<tr>
<td width="22%" height="29">
<div align="right">
<font color="#FF0000">*</font>用户代码:&nbsp;
</div>
</td>
<td width="78%">
<input name="userId" type="text" class="text1" id="userId"
size="10" maxlength="10" onkeypress="userIdOnKeyPress()" onblur="validate(this)"><span id="userIdSpan"></span>
</td>
</tr>
<tr>