加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 01:51:59 所属栏目:百科 来源:网络整理
导读:/** * * @author liang * 需求:模拟注册校验: * 1;jsp页面放置一个text文本框,当用户输入用户名,文本框失去焦点的时候,通过ajax访问服务器 * 2:servlet模拟从数据库中查出用户是否存在,返回给jsp页面一个信息, * 3:jsp页面显示服务器传送过来的信息
/**
*
* @author liang
* 需求:模拟注册校验:
* 1;jsp页面放置一个text文本框,当用户输入用户名,文本框失去焦点的时候,通过ajax访问服务器
* 2:servlet模拟从数据库中查出用户是否存在,返回给jsp页面一个信息,
* 3:jsp页面显示服务器传送过来的信息

*/

jsp页面:

<body>
<div>
用户名:<input type="text" id="username" onblur="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(); } }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读