一个小小的Ajax例子
HTML:
<input type="text" name="username" size="30" maxlength="20" onblur="validate()">
<div id=usermsg></div>
javascript:
<script type="text/javascript">
var req;
function validate(){
var idField = document.getElementById("userid");
var url = "validate.jsp?id=" + escape(idField);
if(window.XMLHttpRequest){
req = new XMLHttpRequest();
alert("ddd");
}else if(window.ActiveXObject){
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open("GET", url , true);
req.onreadystatechange = callback;
req.send(null);
}
function callback(){
if(req.readyState == 4){
if(req.status ==200){
var msg = req.responseXML.getElementsByTagName("msg")[0];
//alert(msg.childNodes[0].nodeValue);
setMsg(msg.childNodes[0].nodeValue);
}
}
}
function setMsg(msg){
if(msg == "invalid"){
document.getElementById("usermsg").innerHTML = "<font color='red'>用户名已存在</font>";
}else{
document.getElementById("usermsg").innerHTML = "<font color='green'>可以注册</font>";
}
}
</script>
validate.jsp
<%
response.setContentType("text/xml");
response.setHeader("Cache-Contorl", "no-store");//HTTP1.1
//response.setHeader("Pragma", "no-cache");//HTTP1.0
response.setDateHeader("Expires", 0);//prevents caching at the proxy server
response.getWriter().write("<msg>invalid</msg>");
%>