使用 xmlhttp 从文本文件读取



我想从文本文件中读取一个单词并使用它来验证密码。当然,我意识到这绝不是安全的,永远不会在现实世界中使用,但这是我必须做的大学课程的作业。每次我点击提交时,我都会被带到"混乱.html"页面,无论密码是否正确......有人可以帮忙吗?

<!DOCTYPE html>
<html>

<body>
<form name="login" onSubmit="return validateForm();" action="messing.html" method="post">
    <label>Password</label>
    <input type="password" name="pword" placeholder="password">
    <input type="submit" value="Login"/>
</form>
<script>
    function validateForm() {
        var user_input = document.login.pword.value;

        xmlhttp=new XMLHttpRequest();
        xmlhttp.open("GET","books.txt",false);
        xmlhttp.send();
        var y =xmlhttp.responseText;


        if (user_input == y){
            return true;
        }
        else {
            alert ("Login was unsuccessful, please check your password");
            return false;
        }
  }
</script>
</body>
</html>

问题是onsubmit .因为您不会阻止表单的默认操作。您的表单被发送到混乱.html将被加载。

当您

要使用 xmlHTTPRequest 时,您需要阻止表单上的默认操作。

function validateForm(e) {
     ....
   e.preventDefault(); //<--- magic

}

附带说明一下。使用同步 xmlHTTPRequest 被认为是不好的做法,在现代浏览器中是不允许的,因为如果没有可用的响应或需要很长时间才能加载,它可能会挂起浏览器。在这种情况下,切换到异步很简单。

function validateForm(e) {
    var user_input = document.login.pword.value;

    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET","books.txt",true); //changed to true
    xmlhttp.onreadystatechange = function(){
     if (this.status == 200 && this.readystate == 4)
     {
       var y =xmlhttp.responseText;
       if (user_input == y){
          location.href = "messing.html";
       }
       else {
          alert ("Login was unsuccessful, please check your password");
          return false;
       }
     }            
    }
    xmlhttp.send();
    e.preventDefault();

}

最新更新