Ajax-用户名是否已被注册 在文本框后面显示“该用户名已被注册”注册表单之校验用户是否注册!1.编写页面ajax3.jsp—给出注册表单页面—给用户名文本框添加onblur事件监听—获取文本框的内容,通过ajax4步发送给服务器,得到响应结果=====如果为1:在文本框后显示“用户名已被注册”2.编写servletJyServlet.java—获取客户端传递的用户参数—判断是否为 zhangsan是:返回1否:返回
0JyServlet.javapackage cn.xtnotes; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class JyServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 1.获取参数username * 2.判断是否为zhangsan * 3.如果是:响应1 * 4.如果不是:响应2 */ String username = request.getParameter("username"); if(username.equalsIgnoreCase("123")) { response.getWriter().print("1"); }else { response.getWriter().print("0"); } } }
<head> <meta charset="utf-8"> <title>Insert title here</title> <script type="text/javascript"> //创建异步对象 function createXMLHttpRequest(){ try{ return new XMLHttpRequest(); }catch(e){ try{ return new ActiveXObject("Msxm12.XMLHTTP"); }catch(e){ try{ return new AtiveXObject("Microsoft.XMLHTTP"); }catch(e){ alert("用的啥浏览器啊?"); throw e; } } } } window.onload=function(){ //获取文本框,给他的失去焦点事件注册监听器 var userEle = document.getElementById("usernameEle"); userEle.onblur = function(){ //1.得到异步对象 var xmlHttp = createXMLHttpRequest(); //2.打开链接 xmlHttp.open("POST","http://127.0.0.1:8080/U8/JyServlet",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){ //双重判断 //获取服务器响应,判断是否为一 //是:获取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>