#2
lmhllr2007-12-05 10:00
|
ajax的基础实例,用于从数据库中检测动态检测用户名是否已经存在(php+mysql,其他只要在test.php程序上改成相应的语言就可以了!)
[bold]test.html:[/bold]
程序代码:
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
</head>
<script language="javascript">
<!--
function AjaxLib()
{
//创建AJAX实例
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (err) {
xmlhttp = null;
}
}
if(!xmlhttp && typeof XMLHttpRequest != "undefined")
xmlhttp = new XMLHttpRequest();
if (!xmlhttp){
return null;
}
return xmlhttp;
}
function AjaxCheck(obj)
{
//判断检测用户名
var xmlObj = AjaxLib();
var objId = obj.id;
var userName = document.getElementById(objId);
var url = "test.php?userName=" + userName.value;
xmlObj.onreadystatechange = function ()
{
if (xmlObj.readyState == 4)
{
var objHelpId = document.getElementById("userNameHelp");
if (xmlObj.responseText == "ok")
{
objHelpId.innerHTML = "可以使用";
}
else
{
objHelpId.innerHTML = "已经有此用户,请更换一个用户名!";
}
}
}
xmlObj.open("GET", url, true);
xmlObj.send(null);
}
-->
</script>
<body>
<form action="" name="f" id="f">
<table border="1" cellspacing="0" width="400" cellpadding="0">
<tr><td>
<div>
<div style="float:left">
user <input type="text" name="userName" onchange="AjaxCheck(this)" id="userName">
</div>
<div id="userNameHelp" style="color:red; float:right">
</div>
</div>
</td></tr>
<tr><td>password <input type="text" name="userPassword" id="userPassword"></td></tr>
</table>
</form>
</body>
</html>
[bold]test.php:[/bold]
程序代码:
<?php
/**
* ajax判断异步判断用户名
*
* 数据库:user; 表:user;
*
*/
//header("Content-Type: text/html; charset=UTF-8\n");
//echo "<meta http-equiv='content-type' content='text/html;charset=utf-8'>";
$link = mysql_connect("localhost", "root", ""); //连接数据库
mysql_select_db("user"); //打开数据库
mysql_query("set names 'utf8'"); //设置字符集
$userName = isset($_GET["userName"]) ? $_GET["userName"] : ""; //取得URL后要检测的用户名
//$userName = "袁相宜";
$userName = iconv("GB2312", "UTF-8", $userName); //把接收的值转换成utf8码
if (empty($userName)) //判断是否是空值
{
echo "fail"
exit();
}
$sql = "SELECT * FROM user WHERE userName = '{$userName}'";
$result = mysql_query($sql, $link);
if (mysql_num_rows($result) > 0)
{
$tip = "fail";
}
else
{
$tip = "ok";
}
echo($tip);
exit(0);
?>