我为我的网站创建了一个 onkeyup 验证用户名的程序。它使用带有 XMLHttpRequest 的 JavaScript。我不知道我的代码有什么问题。js代码是:
function search(username)
{
var xmlhttp, answer;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Sorry, your browser seems to not support XMLHTTP functionality.");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
answer=xmlhttp.responseText;
if(compare_strings(answer,1))
{
document.getElementById("nameInfo").className="error";
document.getElementById("username").className="error";
document.getElementById("nameInfo").innerHTML="Please enter your desired username.";
}
else if(compare_strings(answer,2))
{
document.getElementById("nameInfo").className="error";
document.getElementById("username").className="error";
document.getElementById("nameInfo").innerHTML="The username <strong>"+username+" </strong> is not allowed.";
}
else if(compare_strings(answer,3))
{
document.getElementById("nameInfo").className="error";
document.getElementById("username").className="error";
document.getElementById("nameInfo").innerHTML="The username <strong>"+username+" </strong> has already been taken.";
}
else
{
document.getElementById("nameInfo").className="success";
document.getElementById("username").className="";
document.getElementById("nameInfo").innerHTML="Username <strong>"+username+"</strong> is available.";
flag=1;
}
}
}
var url="ajax_search.php";
url=url+"?q="+username;
url=url+"&sid="+Math.random();
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
/*It has been assumed here that ajax_search.php is in the same directory.*/
xmlhttp.send(null);
}
我的 php 代码有效。当我加载网站并将 aq 放在 .php 后面时?它呼应了正确的答案。无论如何,这是代码:
function chek_avail($username)
{
global $link;
$length=strlen($username);
if($length==0)
$res=1;
else if($length>5 && $length<15)
{
$res=4;
$query = "SELECT * FROM users";
if($result=$link->query($query)){
while($row=$result->fetch_assoc())
{
if(strcmp($username,$row['username'])==0)
$res=3;
}
}
}
else
$res=2;
echo $res;
}
$username=$_GET["q"];
chek_avail($username);
?>
谢谢你的帮助!