doujupa7567 2015-08-31 18:23
浏览 63
已采纳

Javascript使用实时输出验证PHP上的用户名

I want to use Javascript to validate my input username if it is correct or not showing result on realtime. Here is index.html code:

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

Here is the demo3.php code:

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

I use the oninput event example from w3cschools, and I am wondering why my result do not show what I expect? And if I assign $username with static variable, demo3.php result seems to be correct feedback, not from index.html.

Plus, I am wondering how to validate multiple forms, such as password and email within the same validation php file. Ex:

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

New to javascript.All the tutorial seems to provide only one demo, not multiple examples.

  • 写回答

2条回答 默认 最新

  • dongwuzun4630 2015-08-31 20:42
    关注

    Since your input is being placed in the URL, you will need to use the GET parameter other than POST (which does not use the URL):

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

    Now it should be able to pickup your input for $_REQUEST['input'] or $_GET['input']

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥30 用arduino开发esp32控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿