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 cplex运行后参数报错是为什么
  • ¥15 之前不小心删了pycharm的文件,后面重新安装之后软件打不开了
  • ¥15 vue3获取动态宽度,刷新后动态宽度值为0
  • ¥15 升腾威讯云桌面V2.0.0摄像头问题
  • ¥15 关于Python的会计设计
  • ¥15 聚类分析 设计k-均值算法分类器,对一组二维模式向量进行分类。
  • ¥15 stm32c8t6工程,使用hal库
  • ¥15 找能接spark如图片的,可议价
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥15 博通raid 的写入速度很高也很低