简体   繁体   English

通过 Ajax 验证用户名/密码

[英]Validating username/password through Ajax

I am trying to use Ajax to validate a username and password stored in a php document on a server.我正在尝试使用 Ajax 来验证存储在服务器上的 php 文档中的用户名和密码。 The usernames and passwords are pre stored in the document.用户名和密码预先存储在文档中。

On my HTML page is a field for the username, and a field for the password.在我的 HTML 页面上有一个用户名字段和一个密码字段。 Then, when they click the Log-In button it calls the following function:然后,当他们单击“登录”按钮时,它会调用以下函数:

    function checkLogin() {
        var user = document.getElementById("username").value;
        var password = document.getElementById("password").value;
        var data = "userName=" + user + "&password=" + password;

        var request = new XMLHttpRequest();

        request.open("POST", "check.php", false);
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        request.send(data);

        if (request.status === 200) {
            window.open("test.html");
        } else {
            var messageSpan = document.getElementById("response");

            var responseJson = JSON.parse(request.responseText);
            messageSpan.innerHTML = "Your password of " + responseJson["password"] + " was not corerct. Please try again.";
        }
    }

The problem I'm having is that it never gets to the else if the username/password are incorrect.我遇到的问题是,如果用户名/密码不正确,它永远不会到达 else。 Even if there's nothing in the fields, it opens the new page.即使字段中没有任何内容,它也会打开新页面。 What am I doing wrong for it to think that all data is correct?认为所有数据都是正确的,我做错了什么?

NOTE: The above code is for testing purposes only, and won't actually be used when publishing the web page.注意:以上代码仅用于测试目的,在发布网页时不会实际使用。 I just want to see what's happening and get it to work before moving on.我只是想看看发生了什么,并在继续之前让它工作。 Thanks.谢谢。

Most likely your check.php echos out true or false on response in some cases you echo out user ID on success.在某些情况下,您的 check.php 很可能在响应时回显 true 或 false,您在成功时回显用户 ID。 Anyways, your response code is 200 for successful server communication.无论如何,成功的服务器通信的响应代码是 200。 Examine request.responseText in case of getting 200.在得到 200 的情况下检查 request.responseText。

if (request.readyState == 4 && request.status === 200) { 
var responseJson = JSON.parse(request.responseText); 
if (responseJson['success'] == 1){
    window.open("test.html"); 
} else { 
    var messageSpan = document.getElementById("response"); 
    messageSpan.innerHTML = "Your username and password combination was incorrect."; 
}} else {
//For debugging purpose add an alert message here. alert(request.status);
messageSpan.innerHTML = "A server connection error occurred!";  }

It's noticeable that you are sending back json response.很明显,您正在发回 json 响应。 So you may add a node called success whith value of true or false to examine logged in success.因此,您可以添加一个名为 success 的节点,其值为 true 或 false 以检查登录成功。 It's not a good practice to show password in response message though.但是,在响应消息中显示密码并不是一个好习惯。

Well the problem is you are getting status 200 from your check.php every time.那么问题是您每次都从check.php获得状态 200。 In your check.php you need to do some thing like在你的check.php你需要做一些事情

// let validate() be function that validates your username/password     


// and returns true/false on validation

if(validate()){
  http_response_code(200);
} else {
  http_response_code(401);
}

hope it helps希望能帮助到你

simply you can use ajax like this,你可以像这样使用ajax,

   <script>
    function checkLogin() {

    var user = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    $.ajax({
                xhr: function() {
                    var xhr = new window.XMLHttpRequest();
                    //progress        
                    xhr.upload.addEventListener("progress", function(e) {
                        //progress value e                            
                    }, false);
                    return xhr;
                },
                type: "POST",
                url: "check.php",
                data: {'userName' : user , 'password' : password},
                dataType:json,
                success: function(msg) {
                   //when success //200 ok
                 if(msg.status=="done"){
                 window.open("test.html");                      
                  }else{    
    var messageSpan = document.getElementById("response");
    messageSpan.innerHTML = "Your password of " + msg.password+ " was incorrect.";
}

                },
            error: function(jqXHR, textStatus, errorThrown) {
               //when error   
            }
        });
}
</script>

your php server side like this,你的php服务器端是这样的,

    //$status="fail" or "done"
    //success must be always success
$respond=array("success"=>"success","status"=>$status,"password"=>$password);
   echo json_encode($respond);
   exit;

I think this useful for you !我认为这对你有用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM