<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function sendHttpRequest(){
var username=document.getElementById("username").value;
//var password=document.getElementById("#password").value;
//var url="AJAXAction";
var url="AJAXAction?username="+username;
//原生Ajax的发送
//步骤一:创建一个XMLHttpRequest对象,该对象用在ie1.7以上,其他的浏览器都可以顺利的建立相关对象
var xhr=new XMLHttpRequest();
//步骤二:设置请求方式及路径
xhr.open("get",url);
// xhr.open("post",url);
alert(username);
//设置发送请求,使用post发送方式需要设置发送的参数
// xhr.send("username="+username);
xhr.send();
//获取返回的结果,必须要调用回调函数(这个函数都是小写的形式)
xhr.onreadystatechange=function(data){
if(xhr.readyState==4 && xhr.status==200){
//alert(xhr.responseText);
if(xhr.responseText==1){
document.getElementById("userExsitsWarning").style.backgrounColor="yellow";
document.getElementById("userExsitsWarning").style.color="red";
document.getElementById("userExsitsWarning").innerHTML="该用户已经存在!"
alert(data);
}else{
//清空数据
document.getElementById("userExsitsWarning").innerHTML="";
document.getElementById("userExsitsWarning").innerHTML="该用户可以注册!";
}
}
}
}
</script>
</head>
<body>
<div>
<input type="text" id="username" placeholder="请输入用户名:" style="text-indent:15px" onblur="sendHttpRequest()"/>
<span id="userExsitsWarning"></span>
<br/>
<input type="password" id="password" placeHolder="请输入用户密码" style="text-indent: 15px"/>
<br/>
<input type="button" value="开始爽吧!!" onclick="sendHttpRequest()"/>
</div>
</body>
</html>
// 后台方法:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置字符编码样式
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
PrintWriter out=resp.getWriter();
String username = req.getParameter("username");
if(username!=null) {
//使用打印流进行输出,不能使用转发的形式
String str="请求成功!";
out.print("1");
}else {
out.print("0");
}
out.close();
}