我有一个非常基本的代码,我有两个HTML页面,index.html
是一个基本的身份验证页面,crap.html
是我做的页面,好吧,有些废话。
现在,我在index.html
上有一个表单,其上附有onsubmit()
处理程序,以便我可以检查用户名和密码。如果正确,它会显示一条消息并继续将用户重定向到crap.html
现在,问题是这个重定向似乎适用于错误的凭据,但是当给出正确的凭据时,它会自动重新加载index.html
页面,即使auth.js
中没有重定向代码也是如此。
以下是代码:
auth.js
function passCheck(){
var user = document.getElementById("username").value;
var pass = document.getElementById("password").value;
var error = document.getElementById("error");
var set_user = "admin";
var set_pass = "admin";
if(user==set_user && pass==set_pass){
error.style.color="green";
error.innerHTML = "AUTHENTICATED CORRECTLY. REDIRECTING NOW.";
setTimeout(function(){
window.location.href="../crap.html";
}, 3000);
}else{
error.style.color="red";
error.innerHTML = "WRONG CREDENTIALS. REDIRECTING NOW.";
setTimeout(function(){
window.location.href="../index.html";
}, 1000);
}
}
index.html
<html>
<head>
<title>Authentication</title>
<script src="js/jquery.js"></script>
<script src="js/auth.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<form onsubmit="passCheck()">
<table border=0>
<tr>
<td>Username</td>
<td><input type="text" id="username" placeholder="Username" required autofocus></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" id="password" required></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="AUTHENTICATE">
</td>
</tr>
</table>
</form>
<center>
<div id="error"></div>
</center>
</body>
</html>
答案 0 :(得分:2)
它重新加载页面的原因是因为表单被提交到同一页面。您的表单没有动作属性。要阻止表单实际提交,您需要从提交处理程序return false;
。
或者,在提交处理程序中设置表单操作。您可以使用jQuery轻松完成此操作。