使用Ajax简单验证用户名是否重复

来源:互联网 发布:程序员 转行做什么 编辑:程序博客网 时间:2024/05/21 10:13

本例子主要是用于简单验证用户名是否为空,是否重复:

<script type="text/javascript src="../xx.js">

<form action="" enctype="application/x-www-form-urlencoded">

<table border="2">
   <tr>
    <td>用户名:</td>
    <td><input type="text" name="username" id="username">
    <div id="checkname"></div>
    <input type="button" id="checkusername" name="checkusername" value="检测用户名是否被占用">
    </td>
   </tr>
   <tr>
    <td>密码:</td>
    <td><input type="password" id="password" name="password"></td>
   </tr>
  </table>

</from>

编写相关JS代码: xx.js

//声明

function ajaxFunction(){

    var xmlHttp;

    if(window.XMLHttpRequest){

      xmlHttp=new XMLHttpRequest()

    }else if(window.ActiveXObject){

       xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); 

    }

  return  xmlHttp;

}

//使用声明的function

window.onload=functon(){

  document.getElementById("checkusername“).onclick=function(){

       var username=document.getElementById('username').value;

        if(username==""||username=='null'|username=='undefined'){

         alert("用户名不能空");

         document.getElementById("username").focus();

         return false;

        }

       var xmlReq=ajaxFunction();

        xmlReq.onreadystatechane=function(){

            //判断服务器状态

            if(xmlReq.readyState==4&&xmlReq.status==200||xmlReq.status==304){

                 var data=xmlReq.responseText;

                  document.getElementById("checkusername").innerHTML=data;

             }

        }

     //把请求发送给服务器

    xmlReq.open("post","/xx",true);

    xmlReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

 

    //得到客户端的响应

    xmlReq.send(username);

  }

}

连接后台的servlet

访问服务器:http://localhost:8080/xx/xx.jsp

本例子是用Ajax代码简单验证,准确的验证除了在页面验证之外,输入的数据应该在数据库中对比。

原创粉丝点击