您现在的位置: 万盛学电脑网 >> 程序编程 >> 网络编程 >> php编程 >> 正文

php ajax用户注册检测代码

作者:佚名    责任编辑:admin    更新时间:2022-06-22

实只要简单的实现ajax的检测用户名,正规点要分三个文件。我这里简单点:

第一个:index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.hake.cc/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.hake.cc/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script language="javascript" src=http://www.phpzy.com/PHPjichu/"ajax.js"></script>
</head>

<body>
<table align="center">
<tr>
     <td width="25%" class="altbg1"> 用 户 名<font color="red">*</font>
    <input size="25" name="username" id="username" type="text" value="" onblur="startRequest(document.getElementById('username').value);" />       <br /></td>
              <td></td>
                          <td id="ckuser"></td>
</tr>
</table>
</body>
</html>
第二个要用到js:ajax.js
[php]

var xmlHttp;
function createXMLHttpRequest()
{
      if(window.XMLHttpRequest)
{
      xmlHttp = new XMLHttpRequest();//mozilla浏览器
}
else if(window.ActiveXObject)
{
try
{
     xmlHttp = new ActiveX0bject("Msxml2.XMLHTTP");//IE老版本
}
catch(e)
{}
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");//IE新版本
}
catch(e)
{}
if(!xmlHttp)
{
window.alert("不能创建XMLHttpRequest对象实例");
return false;
}
}
}


function startRequest(username)
{
createXMLHttpRequest();//特编

xmlHttp.open("GET","ckuser.php?name="+username,true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.send(null);
}


function handleStateChange()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
//alert("来自服务器的响应:" + xmlHttp.responseText);
if(xmlHttp.responseText == "true"){
document.getElementById("ckuser").innerHTML = '此用户名以被人注册';
}
else if(xmlHttp.responseText == "false")
{
document.getElementById("ckuser").innerHTML = '检测通过';
}
}
}
}

[/php]

第三个文件就是php文件:ckuser.php
<?php
        require_once("conn.php");
   $username = $_GET["name"];
        $query="select id from user where username='".$username."';";
        $res=mysql_query($query);
                if(mysql_num_rows($res)!=0)
                {
             echo "true";
                }else
                        {
                           echo "false";
                        }


?>
最后一个是数据库链接文件conn.php

<?php
     $conn=mysql_connect("localhost","root","l1314520") or die("数据库服务器连接错误".mysql_error());
     mysql_select_db("test",$conn) or die("数据库访问错误".mysql_error());
   mysql_query("set character set gb2312");
     mysql_query("set names gb2312");
?>