dqsxsmi3704 2015-07-05 17:32
浏览 32
已采纳

使用AJAX检查用户名可用性

I'm currently trying to develop a small website in PHP to test my skills. However I found myself stuck when I decided to implement a live username availability check for the sign up process, as my JavaScript knowledge is somewhat basic.

Right now when I put some name in the username field, I only get the loading image and nothing else. This is what I have done:

My login.php page stored in the /views folder:

<section>
    <div>
        <form action="?action=login" method="post">
            <input type="text" placeholder="username" name="username" id="username" onkeypress ="check()">
            <span id="usernameStatus"></span>
        </form>
    </div>
</section>

My js file stored in /views/js:

function check () {
    var status = document.getElementById('usernameStatus');
    var u = document.getElementById('username').value;
    if(u != ""){
        status.innerHTML = '<img src="views/img/wait.gif" alt="" height="20" />';
        var hr = new XMLHttpRequest();
        hr.open("POST", "../login.php", true);
        hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        hr.onreadystatechange = function() {
            if(hr.readyState == 4 && hr.status == 200) {
                status.innerHTML = hr.responseText;
            }
        }

        var v = "checkName="+u;
        hr.send(v);

    }
}

And finally the loginController.php stored in /controllers:

    public function run() {
        if(!empty($_POST["checkName"])){
            $name= htmlentities($_POST["checkName"]);
            if(Db::getInstance()->username_ok($name)){
                echo ("<strong>" . $name . "</strong> unavailable");
            }
            else{
                echo ("<strong>" . $name . "</strong> available");
            }
        }
        require_once('views/login.php');
    }

Could someone explain me what have I done wrong? Thanks!

  • 写回答

2条回答 默认 最新

  • douchui7332 2015-07-05 19:25
    关注

    I think the problem is with filenames.

    From your question, I guess the file structure is

    root
    |-- controllers
    |   `-- loginController.php
    `-- views
        `-- js
            `-- script.js
    

    In your JavaScript code which is in the file views/js/scriptname.js,

    hr.open("POST", "../login.php", true);
    

    request is sent to the file login.php.

    But, as you have mentioned, the path to your server side php script is /controllers/loginController.php.

    According to me, the JavaScript code should be as following:

    hr.open("POST", "controllers/loginController.php", true);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理