我已经为提交按钮调用了验证功能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;
)
}
答案 0 :(得分:0)
您未在validate
函数中验证任何内容。至少添加一个基本检查,如下变量是否为空。
var username = document.getElementById("username_input").value;
var password = document.getElementById("password_input").value;
if (username.trim() == "" || password.trim() == "") return false;
答案 1 :(得分:0)
试试这个。它正在运作。它不起作用的原因是因为您没有检查ajax请求的状态和readystate。
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();
}
}
}
}
希望这有帮助,谢谢