Ajax检查用户名是否存在

时间:2012-05-07 12:18:05

标签: php javascript html ajax

我无法让我的代码正常工作。当用户键入用户名时,它会检查数据库以查看它是否存在以及是否将<P id="checkusername">设置为“用户名”。如果没有设置为“未采取”。我看不出为什么我的代码无效。

1-register.html

<html>
  <body>
    <CENTER>
      <form name="register" action="register.php" method="post">
        Username: <input type="text" name="username" onkeyup="checkUsername(this.value)" />
        <P id="checkusername">checker</P> 
        <input type="submit" value="Login" />      
      </form>
    </CENTER>

    <script type="text/javascript">
      function checkUsername(){
        var xmlhttp;
        var username=document.forms["register"]["username"].value;
        if(username.length==0){
          document.getElementById("checkusername").innerHTML="Empty";
          return;
        }
        if(window.XMLHttpRequest){
          xmlhttp=new XMLHttpRequest();
        }else{
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }

        var url = "login.php";
        var params = "header=checkusername&username="+username+"&password="";
        xmlhttp.open("POST", url, true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.setRequestHeader("Content-length", params.length);
        xmlhttp.setRequestHeader("Connection", "close");

        xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
          document.getElementById("checkusername").innerHTML=xmlhttp.responseText;
    }
      }
      xmlhttp.send(params);
    }
    </script>
  </body>
</html>

2-register.php

<?php
  $header = $_POST["header"];
  if(header=="checkusername"){
    checkusername($_POST["username"]);
  }else{
    echo "No match: " . $header;
  }

  function connection(){
    $con = mysql_connect(URL, username, password);
    if(!$con){
      die('Could not connect: ' . mysql_error());
    }
    return $con;
  }
  function checkusername($username){
    $con = connection();
    mysql_select_db(database, $con);
    $result = mysql_query("SELECT * FROM users WHERE username = \"" . $username . "\";");
    while($row = mysql_fetch_array($result)){
      if(($row['username'] == $username)){
        echo "Username Taken.<br/>";
        return;
      }
    }
    echo "Not Taken.";
  }
  mysql_close();
?>

1 个答案:

答案 0 :(得分:3)