dpymrcl269187540 2016-03-14 04:57
浏览 53
已采纳

通过Ajax验证用户名/密码

I am trying to use Ajax to validate a username and password stored in a php document on a server. 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. 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 incorrect.";
        }
    }

The problem I'm having is that it never gets to the else if the username/password are incorrect. 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.

  • 写回答

3条回答 默认 最新

  • dqouryz3595 2016-03-14 05:18
    关注

    Most likely your check.php echos out true or false on response in some cases you echo out user ID on success. Anyways, your response code is 200 for successful server communication. Examine request.responseText in case of getting 200.

    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. So you may add a node called success whith value of true or false to examine logged in success. It's not a good practice to show password in response message though.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器