我已经为提交按钮调用了验证函数onclick。 HTML即使信息无效,Ajax登录表单也会被提交
<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;
)
}
什么validate.php样子?也许错误在那个文件中? – putvande
由于提交按钮的默认操作,我猜你的表单正在提交。你可以尝试在form标签中加入'onsubmit =“return false;”'吗? – Harry
'onclick =“return validate()”'? –