正在跳过XMLHttpRequest.onreadystatechange函数

时间:2017-03-24 03:45:53

标签: javascript php ajax

我正在尝试使用嵌入式javascript和一个AJAX请求在php中创建一个注册页面,该请求将告诉我当前用户名是否被使用并显示一条消息让我知道。

的index.php:

<?php
    require_once 'functions.php';
    //Javascript code to see if username is available
    echo <<<_END
        <script>
        function checkUser(user) {
            if(user.value == '') {
                document.getElementById('available').innerHTML = ''
                return
            }

            params = "user=" + user.value
            request = new ajaxRequest()
            request.open("POST", "checkuser.php", true)
            request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            request.setRequestHeader("Content-length", params.length);
            request.setRequestHeader("Connection", "close");

            request.onreadystatechange = function() {
                //NEVER GET INTO THIS FUNCTION
                console.log("ON READY STATE CHANGE FUNCTION");
                if(this.readyState == 4 && this.status == 200) {
                    document.getElementById('available').innerHTML = this.responseText;
                }
                request.send(params)
            }
        }

        function ajaxRequest() {
            try {
                var request = new XMLHttpRequest() //Probably going to be this one
            } catch(e1) {
                //Other types of requests
                request = false
            }
            return request
        }
        </script>
_END;
//More php code here that i deemed not relevant
?>

<html>
    <h1>Sign Up</h1><body>
        <form class = "form-signin" role = "form" 
        action = "<?php echo htmlspecialchars($_SERVER['PHP_SELF']); 
        ?>" method = "post">
        <label for="username">Username:</label>
        <input name="user" type="text" onBlur="checkUser(this)"><span id="available"></span><br>
        <label for="password">Password:</label>
        <input name="pass" type="password"><br>
        <button class = "btn btn-lg btn-primary btn-block" type="submit" name="login"><br>
    </body>
</html>

这是checkuser.php:

<?php
    require_once 'functions.php'
    if(isset($_POST['user'])) {
        $username = $_POST['user'];
        $result = querySQL("SELECT * FROM USER
                                WHERE username='$username'");
        if($result->num_rows) {
            echo "This username is taken";
        } else {
            echo "This username is available";
        }
    }
?>

现在我在firefox中的开发人员控制台中查看了代码,除了index.php中的request.onreadystatechange = function()部分之外,所有内容似乎都正常工作它命中了声明此函数的行,但它从不进入函数。

1 个答案:

答案 0 :(得分:0)

问题在于您的PHP代码。

onreadystatechange甚至只会在收到服务器的响应或请求超时时触发。

由于您不是request.send(data)或正在做任何请求,Ajax正在等待服务器响应