我已经为提交按钮调用了验证函数 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;
)
}