0

我已经为提交按钮调用了验证函数 onclick。HTML

<form role="form" style="margin:0 20px 0 0; float:right" method="post" action="login.php" id="loginform">
    <h3>Login</h3>
    <div class="form-group" >
        <label>Username</label>
        <input type="text" class="form-control" placeholder="Enter username" name='username' id="username_input">
        <label >Password</label>
        <input type="password" class="form-control"  placeholder="Password" name="password" id="password_input">
    </div>
    <div id="login_feedback"></div>
    <input type="submit" value="Login" onclick="validate()"></input><br/>   
</form>

JS

表单总是被提交。我只想在 responseText “正确”时提交

 function validate() {
   var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    else {
        throw new Error("Ajax is not supported by this browser");
    }
    var username = document.getElementById("username_input").value;
    var password = document.getElementById("password_input").value;
    xhr.open('POST', 'validate.php');
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("username=" + username + "&password=" + password );    
    xhr.onreadystatechange = function () {
            var data=xhr.responseText.trim();
            document.getElementById("login_feedback").innerHTML = data;
            if (data=='correct'){
                     document.getElementById("loginform").submit();
                }
    } 
    return false;
    )

}
4

2 回答 2

0

您没有验证validate函数中的任何内容。至少添加如下基本检查,以查看变量是否为空。

var username = document.getElementById("username_input").value;
var password = document.getElementById("password_input").value;
if (username.trim() == "" || password.trim() == "") return false;
于 2013-08-16T10:10:28.853 回答
0

试试这个。它正在工作。它不起作用的原因是您没有检查 ajax 请求的状态和就绪状态。

function validate() {

   var xhr;
     if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    else {
        throw new Error("Ajax is not supported by this browser");
    }

    var username = document.getElementById("username_input").value;
    var password = document.getElementById("password_input").value;
    xhr.open('POST', 'validate.php',true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("username=" + username + "&password=" + password );   
    xhr.onreadystatechange = function () {
 if (xhr.readyState==4 && xhr.status==200)   //this is needed
    {
    var data=xhr.responseText.trim();
            document.getElementById("login_feedback").innerHTML = data;
            if (data=='correct'){
                     document.getElementById("loginform").submit();
                }
    }

    } 
   }

希望这会有所帮助,谢谢

于 2013-08-16T11:20:35.107 回答