<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>
<input type="text" id="name" onblur="sendAjax()"/>
<img src="img/ajax.gif" style="display:none" id="loading"/>
<span id="result"></span>
<br/>
<!--
<input type="button" value="Send Ajax" onclick="sendAjax()"/>
-->
<script type="text/javascript">
var xmlHttp;
/*创建XMLHttpRequest对象*/
function createXMLHttpRequest() {
if(window.ActiveXObject) {
//IE
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
//chrome firefox opera
xmlHttp = new XMLHttpRequest();
}
}
function sendAjax(){
createXMLHttpRequest();
var name = document.getElementById("name").value;
//post
xmlHttp.open("POST", "ajax.jspx", true);
xmlHttp.onreadystatechange = callback;
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send("name="+name);
//get
//xmlHttp.open("GET","ajax.jspx?name="+name,true);
//xmlHttp.onreadystatechange = callback;
//xmlHttp.send();
}
function callback() {
if(xmlHttp.readyState == 4) {//服务器响应返回
document.getElementById("loading").style.display = "none";
if(xmlHttp.status == 200) {//响应正确
var result = xmlHttp.responseText;
if(result == "ok") {
document.getElementById("result").innerHTML = "√";
} else {
document.getElementById("result").innerHTML = "用户名已占用";
}
} else {
alert("Ajax Error!");
}
} else {
//进度条
document.getElementById("loading").style.display = "inline";
}
}
</script>
</body>
</html>