使用Ajax进行验证

I wrote some ajax code that sends values to a php file for validation but I have a problem with it. This is my ajax code:

<html>
<body>
<style>
#displayDiv{
background-color: #ffeeaa;
width: 200;
}
</style>
<script type="text/javascript">
function ajaxFunction(str)
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateChanged()
{
if(httpxml.readyState==4)
{
document.getElementById("displayDiv").innerHTML=httpxml.responseText;

}
}
var url="username_exists.php?username=";
httpxml.onreadystatechange=stateChanged;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
</head>
<body>
<input type="text"
onkeyup="ajaxFunction(this.value);" name="username" /><div id="displayDiv"></div>
</body>
</html>

and the above code send values to username_exists.php :

<?php
$username = trim($_REQUEST['username']);

if (usernameExists($username)) {
  echo '<span style="color:red";>Username Taken</span>';
}
else {
  echo '<span style="color:green;">Username Available</span>';
}

function usernameExists($input) {
  // in production use we would look up the username in
  // our database, but for this example, we'll just check
  // to see if its in an array of preset usernames.
  $name_array =  array ('k','steve', 'jon', 'george', 'admin');

  if (in_array($input, $name_array)) {
    return true;
  }
  else {
    return false;
  }
}
?>

My problem is that when any username is put in the textbox returns "Username Available"! What did I do wrong?

You are sending an empty string as username to check thru your ajax call.

var url="username_exists.php?username=";

I would suggest you to start using jQuery to help you in handling this case.You don't need to worry about the cross browser issue and you dont need to write all these lines of code.

jQuery is a wonderful javascript library. http://www.jquery.com

Include jquery library (i will use the CDN Version) in your head section of HTML document and change your code like this.

HTML

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 
</head>
<body>
<input type="text" id=txtUserName"  />
</body>

javascript

  $("#txtUserName").keyUp(function(){
   if($("#txtUserName").val()!="")
   {
      $.ajax({
        url: 'username_exist.php?username'+$("#txtUserName").val(),
        success: function(data) {
                alert(data);
        }
      });
  }
}