使用ajax验证用户名是否被注册

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>




<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'ajax3.jsp' starting page</title>
    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
//创建异步对象,直接一步到位所有浏览器
function createXMLHttpRequest() {
try {
return new XMLHttpRequest();//大多数浏览器
} catch (e) {
try {
return ActvieXObject("Msxml2.XMLHTTP");//IE6.0
} catch (e) {
try {
return ActvieXObject("Microsoft.XMLHTTP");//IE5.5及更早版本
} catch (e) {
alert("哥们儿,您用的是什么浏览器啊?");
throw e;
}
}
}
}




window.onload = function() {
// 获取文本框元素,给它的失去焦点事件注册监听
var userEle = document.getElementById("usernameEle");
userEle.onblur = function() {
//1.得到异步对象
var xmlHttp = createXMLHttpRequest();
//2.打开连接
xmlHttp.open("POST", "<c:url value='/ValidateUsernameServlet'/>", true);
//3.设置请求头:Content-Type
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//4.发送请求,给出请求体
xmlHttp.send("username=" + userEle.value);

//5.给xmlHttp的onreadystatechange事件注册监听
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {//双重判断
//获取服务器的响应,判断是否为1
// 是:获取span,添加内容:“用户名已被注册”

var text = xmlHttp.responseText;

//得到span元素

var span = document.getElementById("errorSpan");
if(text == "1") {

span.innerHTML = "用户名已被注册!";
} else {
span.innerHTML = "";
}
}
};
};
};
</script>
  </head>
  
  <body>
<h1>演示用户名是否被注册</h1>
<form action="" method="post">
用户名:<input type="text" name="username" id="usernameEle"/><span id="errorSpan"></span><br/>
密 码:<input type="password" name="password"/><br/>
<input type="submit" value="注册"/>
</form>
  </body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值