萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> php ajax用戶注冊檢測代碼

php ajax用戶注冊檢測代碼

實只要簡單的實現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");
?>

copyright © 萬盛學電腦網 all rights reserved