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条)

报告相同问题?

悬赏问题

  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测