ajax之判断用户名是否被注册

/**
 * 
 * @author liang
 * 需求:模拟注册校验:
 * 1;jsp页面放置一个text文本框,当用户输入用户名,文本框失去焦点的时候,通过ajax访问服务器
 * 2:servlet模拟从数据库中查出用户是否存在,返回给jsp页面一个信息,
 * 3:jsp页面显示服务器传送过来的信息

 */

jsp页面:

<body>
<div>
用户名:<input type="text" id="username" οnblur="sendmessage()"/><span id="warn"></span>
</div>
</body>

js脚本:

<script>
//得到浏览器的xmlHttpRequest对象
function createXmlHttpRequest(){
var xmlHttp ;
try{
//适用于大部分的浏览器
xmlHttp = new XMLHttpRequest();
}catch(e){
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlHttp = new ActiveXOject("Microsoft.XMLHTTP");
}catch(e){
throw e;
}
}
}
return xmlHttp;
}
function sendmessage (){
//四步
//1:得到XMLHttpRequest对象
var xmlHttp = createXmlHttpRequest();
//打开与浏览器的连接,因为要发送数据,所以才用post请求
xmlHttp.open("POST","Login_servlet",true);
//设置请求的格式
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//发送数据
var  username = document.getElementById("username").value;

xmlHttp.send("username="+username);
//得到服务器的响应,并显示在页面上
xmlHttp.onreadystatechange = function(){
if(xmlHttp.status == 200 && xmlHttp.readyState == 4){
if(xmlHttp.responseText == true)
document.getElementById("warn").innerHTML = "该用户已经被注册!!!";
else
document.getElementById("warn").innerHTML = xmlHttp.responseText;
}
}
}


</script>

 servlet的post方法:

public class Login_servlet extends HttpServlet {
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String username = request.getParameter("username");
if(username.trim().equals("admin")){
response.getWriter().print("合法用户,可以登陆!!!");
response.getWriter().flush();
}else{
response.getWriter().print("你是土匪派过来,砸场子的吧");
response.getWriter().flush();
}
if(response.getWriter()!= null)
response.getWriter().close();
}


}



























  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值