ajax+php验证用户名重复代码实例
本教程是一款利用了ajax php在用户输入完用户名后,就会发送请求给php程序,然后查询数据,判断用户要注册的用户名是不是己经注册或存在重复了,及时的返回提示信息,以免用户填写了一大填表单后,突然提供用户名不能注册己被注册了,这样体验就不好了,本教程就是专门解决这个问题了,能快速的告诉你要注册的用户名是否可以注册.
<!doctype html>
<html xmlns="http://www.phprm.com/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title>ajax+php验证用户名重复代码实例</title>
<script language="javascript">
function createxmlhttprequest() { //创建xmlhttprequest对象
if (window.activexobject) { //ie
try {
return new activexobject("microsoft.xmlhttp");
} catch (e) {
return;
}
} else if (window.xmlhttprequest) { //mozilla,firefox
try {
return new xmlhttprequest();
} catch (e) {
return;
}
}
}
function getrenews(value) { //主调函数
var xmlhttp = createxmlhttprequest();
var url = "13.php?action=check&title=" + value + "&mt=" + math.random(300000);
if (value == "") {
return false;
}
if (xmlhttp) {
callback = getreadystatehandler(xmlhttp);
xmlhttp.onreadystatechange = callback;
xmlhttp.open("get", url, true);
xmlhttp.send(null);
}
}
function getreadystatehandler(xmlhttp) { //服务器返回后处理函数
return function () {
if (xmlhttp.readystate == 4) {
if (xmlhttp.status == 200) {
alert(xmlhttp.responsetext);
if (xmlhttp.responsetext == 1) {
document.getelementbyid("checkid").innerhtml = "<font color='red'>对不起,用户名己存在!</font>";
} else {
document.getelementbyid("checkid").innerhtml = "可以注册";
}
}
}
}
}
</script>
</head>
<body>
<table width="75%" border="0">
<tr>
<td width="12%">输入用户名</td>
<td width="36%">
<input type="text" name="username" id="username" onblur="getrenews(this.value);" />
</td>
<td width="52%" id="checkid"> </td>
</tr>
</table>
</body>
</html>把下面代码保存忝13.php,代码如下:
<?php
checkusername();
function checkusername() {
$title = trim($_get['title']);
if (emptyempty($title)) {
return false;
} else {
mysql_connect('localhost', 'root', 'root');
mysql_select_db('test');
mysql_query("set names 'gb2312'");
$sql = "select * from cn_user where username ='$title'";
$row = mysql_query($sql);
if (mysql_num_rows($row)) {
echo 1;
} else {
return null;
}
}
}创建数据库SQL代码如下:
create table `test`.`cn_user` ( `id` int not null auto_increment , `username` varchar( 20 ) not null , `times` date null , primary key ( `id` ) ) engine = myisam //插入数据 insert into `test`.`cn_user` ( `id` , `username` , `times` ) values ( null , 'jimmy', null ), ( null , 'www.phprm.com', null );
本文地址:http://www.phprm.com/develop/fs5402.html
转载随意,但请附上文章地址:-)