Javascript通过实时输出在PHP上验证用户名


Javascript validate username on PHP with realtime output

我想使用Javascript来验证我的输入用户名,如果它是正确的或不显示实时结果。以下是index.html代码:

<html>
<head>
<script>
function showHint(str){
    if(str.length == 0){
        document.getElementById("hint").innerHTML = "";
    }else{
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function(){
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                document.getElementById("hint").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("POST", "demo3.php?input=" + str, true);
        xmlhttp.send();
    }
}
</script>
</head>
<body>
Type a username: <br>
<input id="hint" type="text" name="username" oninput="showHint(this.value)"><p id="hint"></p>
</body>
</html>
下面是demo3.php代码:
<html>
<head>
</head>
<body>
<?php
$mysqli = new mysqli("localhost","root","123456","mini");
$username = $mysqli->real_escape_string($_REQUEST['input']);
$sql = "SELECT username FROM `users` WHERE username='$username'";
    $result = $mysqli->query($sql);
    if($result->num_rows){
        echo "Valid username";
    }else{
        echo "Invalid username";
    }
?>
</body>
</html>

我使用的oninput事件的例子从w3cschools,我想知道为什么我的结果不显示我所期望的?如果我分配$username与静态变量,demo3.php的结果似乎是正确的反馈,而不是从index.html。

另外,我想知道如何验证多个表单,如密码和电子邮件在同一个验证php文件。例:

input1 -> check username ->output check result
input2-> check password ->output check result
input3-> check email->output check result

javascript新功能。所有的教程似乎只提供了一个演示,而不是多个例子。

由于您的输入被放置在URL中,您将需要使用GET参数而不是POST(不使用URL):

xmlhttp.open("GET", "demo3.php?input=" + str, true);

现在它应该能够拾取input$_REQUEST['input']$_GET['input']

问题是您使用了两次ID "hint"。ID是一个唯一的标识符,所以你永远不应该在同一个页面中使用它多次。并且应该避免使用内联处理程序。您需要将javascript更改为:

<script>
window.onload = function() {
 function showHint(str){
    if(str.length == 0){
        document.getElementById("hint").innerHTML = "";
    }else{
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function(){
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                document.getElementById("hint").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("POST", "demo3.php?input=" + str, true);
        xmlhttp.send();
    }
 }
 document.getElementById("hintInput").onkeyup = function() {
  showHint(this.value)
 }
}
</script>

和你的HTML:

<input id="hintInput" type="text" name="username"><p id="hint"></p>

如果您在关闭body标签之前放置脚本标签,则可以摆脱window.onload