登录验证 JavaScript 无法正常工作



所以我有这个登录表单,用于检查数据库中是否存在用户以及密码和用户名是否匹配。如果出现问题,则会出现错误消息,但尽管如此,即使用户错误,也可以提交他的答案!在答案正确之前,如何阻止提交按钮?

<form
  id="login"
  action="loginController1.jsp"
  onsubmit="return validateLogin()"
>
  <input
    id="username"
    name="username"
    type="text"
    placeholder="Username"
    autofocus
    onkeyup="validateUsername()"
    required
  />
  <span id="loginstatus"> </span>
  <input
    id="password"
    name="password"
    type="password"
    placeholder="Password"
    onkeyup="validateLogin()"
    required
  />
  <span id="loginstatus1"> </span>
  <input type="submit" id="submit" value="Log in" />
</form>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
  function validateUsername() {
    var xmlhttp;
    var u = document.getElementById("username").value;
    var urls = "checkLogin.jsp?uname=" + u;
    if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
    // code for IE7+, Firefox, Chrome, Opera, Safari
    else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
    xmlhttp.onreadystatechange = function () {
      if (xmlhttp.readyState == 4)
        document.getElementById("loginstatus").innerHTML = xmlhttp.responseText;
    };
    xmlhttp.open("GET", urls, true);
    xmlhttp.send();
  }
</script>
<script type="text/javascript">
  function validateLogin() {
    var xmlhttp;
    var u = document.getElementById("username").value;
    var p = document.getElementById("password").value;
    var urls = "checkLogin1.jsp?uname=" + u + "&pwd=" + p;
    if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
    // code for IE7+, Firefox, Chrome, Opera, Safari
    else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
    xmlhttp.onreadystatechange = function () {
      if (xmlhttp.readyState == 4)
        document.getElementById("loginstatus1").innerHTML =
          xmlhttp.responseText;
    };
    xmlhttp.open("GET", urls, true);
    xmlhttp.send();
  }
</script>

尝试默认禁用该按钮:

<input type="submit" id="submit" value="Log in" disabled="true">

然后在验证登录中添加一行以启用按钮:

xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4)
        document.getElementById("loginstatus1").innerHTML=xmlhttp.responseText;
    else
        document.getElementById("submit").disabled = false;
}

您可能还希望将以下行添加到每个验证函数的顶部:

document.getElementById("submit").disabled = true;

否则,用户可以遵循以下顺序:

  1. 用户输入有效的用户名和密码
  2. 您的代码验证条目并启用登录按钮
  3. 用户将登录名或密码更改为无效的内容
  4. 用户单击"提交"按钮

相关内容

  • 没有找到相关文章

最新更新