一个很好的ajax入门小实例,用户登录验证

前端之家收集整理的这篇文章主要介绍了一个很好的ajax入门小实例,用户登录验证前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
js代码
  <script type="text/javascript">   
        var xmlHttp;    
        function createXMLHttpRequest() {    
            if (window.ActiveXObject) {    
                   xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");    
            }    
            else if (window.XMLHttpRequest) {    
                xmlHttp = new XMLHttpRequest();    
            }
        }    
        function startRequest(url) {
            createXMLHttpRequest();
            xmlHttp.open("GET",url,true);    
               xmlHttp.onreadystatechange = showResult;
            xmlHttp.send(null);
        }    
        function showResult() {    
            if(xmlHttp.readyState == 4) {    
                if(xmlHttp.status == 200) {
                    var res=xmlHttp.responseXML.getElementsByTagName("res")[0].firstChild.data;
                    loginResult("loginResult",res);
                }    
            }    
        }
        
        function loginResult(divId,result){
            var responseDiv = document.getElementById(divId);
                    if(responseDiv.hasChildNodes()){
                        responseDiv.removeChild(responseDiv.childNodes[0]);
                    }
                var responseContent = document.createTextNode(result);
                responseDiv.appendChild(responseContent);
        }
        function validateUser(){
            var userName = document.loginForm.username.value;
            var password = document.loginForm.pwd.value;
            startRequest('loginServlet?userName='+userName+'&password='+password);
        }
        function checkUserName(){
            var userName = document.loginForm.username.value;
            if(userName==""){
                loginResult("username","用户名不能为空");
            }
            else
                loginResult("username","");
        }
        function checkPassword(){
            var userName = document.loginForm.pwd.value;
            if(userName==""){
                loginResult("pwd","密码不能为空");
            }
            else
                loginResult("pwd","");
        }
        </script>
登录页面html
<body>
        <form action="#" name="loginForm">
        用户名<input type="text" name="username" onblur="checkUserName();"/>
        <font color="red" id="username"></font><br>
        密码<input type="password" name="pwd" onblur="checkPassword();"/>
        <font color="red" id="pwd"></font><br>
        <input type="button" value="登录" onclick="validateUser();"/>
        <input type="reset" value="重置"/>
        <font color="red" id="loginResult"></font><br>
    </form>
    </body>
</html>
原文链接:https://www.f2er.com/ajax/165671.html

猜你在找的Ajax相关文章