Ajax实现判断用户名是否已被注册
1.初始化对象,建立连接,并发送消息
1 <script type="text/javascript"> 2 function checkUser(username){//检测是否为空,不为空进行异步检测 3 if(username.value == ""){ 4 alert("请输入用户名!"); 5 username.focus(); 6 return; 7 } 8 else{ 9 createRequest('checkUser.jsp?user='+username.value); 10 } 11 } 12 function createRequest(url){//初始化对象,建立连接,并发送请求 13 var xmlhttp; 14 if(window.XMLHttpRequest){ 15 //code for IE7+,Firefox,Chrome,Opera,Safari 16 xmlhttp = new XMLHttpRequest(); 17 }else{ 18 //code for IE6,IE5 19 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 20 } 21 if(!xmlhttp){//如果不存在 22 alert("不能创建XMLHttpRequest对象实例"); 23 return false; 24 } 25 xmlhttp.onreadystatechange = function(){ 26 if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ 27 document.getElementById("myDiv").innerHTML=xmlhttp.responseText; 28 } 29 } 30 xmlhttp.open("GET",url,true); 31 xmlhttp.send(); 32 } 33 </script>
2.body表单:
1 <body> 2 <form action="" method="post" name="form1"> 3 <center>用户名:<input type="text" id="username" size="32"> 4 <input type="button" onclick="checkUser(form1.username)" value="check"></center><br> 5 <center>密码:<input type="password" id="pwd1" size="32"></center><br> 6 <center>确认密码:<input type="password" id="pwd2"></center><br> 7 <center>E-mail:<input type="text" id="email"></center><br> 8 <center><input type="submit" value="register"></center><br> 9 </form> 10 <center><div id="myDiv"></div></center> 11 </body>
3.checkUser页面验证信息:
1 <% 2 String[] userList = {"baidu","taobao","qq"};//已注册的用户名用数组暂存 3 String user = new String(request.getParameter("user").getBytes("ISO-8859-1"),"UTF-8"); 4 Arrays.sort(userList); 5 int result=Arrays.binarySearch(userList, user); 6 if(result > -1){ 7 out.print("该用户已经被注册"); 8 }else{ 9 out.print("恭喜您,该用户没有注册"); 10 } 11 %>