本教程是一款利用了ajax php在用户输入完用户名后,就会发送请求给php程序,然后查询数据,判断用户要注册的用户名是不是己经注册或存在重复了,及时的返回提示信息,以免用户填写了一大填表单后,突然提供用户名不能注册己被注册了,这样体验就不好了,本教程就是专门解决这个问题了,能快速的告诉你要注册的用户名是否可以注册.
- <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
- <html xmlns="http://www.phpfensi.com/1999/xhtml">
- <head>
- <meta http-equiv="content-type" content="text/html; charset=gb2312" />
- <title>ajax+php验证用户名重复代码实例</title>
- <script language="javascript">
- function createxmlhttprequest(){
- if(window.activexobject){
- try {
- return new activexobject("microsoft.xmlhttp");
- } catch(e){
- return;
- }
- }else if(window.xmlhttprequest){
- 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.phpfensi.com', null
- );
|