当前位置:首页 > 综合实例 > 列表

php+ajax注册验证实例(完整代码)

发布:smiling 来源: PHP粉丝网  添加日期:2015-04-10 14:37:34 浏览: 评论:0 

ajax注册是现在我看到网站中所有网站几乎都会使用到的一个功能,下面我就来给各位整理一个关于ajax注册验证例子,希望此例子能帮助到各位哦.

html代码如下:

  1. <script src="ajax.js"></script>  
  2. <form>  
  3. <table> 
  4. <tr> 
  5.   <td>用户名:</td> 
  6.   <td><input type="text" id="txt1" onKeyUp="showHint(this.value)"></td> 
  7.  </tr> 
  8.  <tr align="center"> 
  9.   <td colspan="2"><span id="txtHint"></span></td> 
  10.  </tr> 
  11. </table> 
  12. </form> 

js文件代码如下:

  1. var xmlHttp 
  2. function showHint(str) 
  3. { 
  4. if (str.length==0) 
  5.   {  
  6.   document.getElementById("txtHint").innerHTML="" 
  7.   return 
  8.   } 
  9. xmlHttp=GetXmlHttpObject() 
  10. if (xmlHttp==null) 
  11.   { 
  12.   alert ("Browser does not support HTTP Request") 
  13.   return 
  14.   }  
  15. xmlHttp.onreadystatechange=stateChanged 
  16. var geturl="conn.php?q="+str 
  17. //sid是增加一个随机数 防止页面启用缓存技术· 
  18. geturl=geturl+"&sid="+Math.random() 
  19. geturl=encodeURI(geturl); 
  20. geturl=encodeURI(geturl);  
  21. xmlHttp.open("GET",geturl,true) 
  22. xmlHttp.send(null) 
  23. }  
  24. function stateChanged()  
  25. {  
  26. if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") 
  27.  {  
  28.  document.getElementById("txtHint").innerHTML=xmlHttp.responseText  
  29.  }  
  30. } 
  31. function GetXmlHttpObject() 
  32. { 
  33. var xmlHttp=null; 
  34. try 
  35.  { 
  36.  // Firefox, Opera 8.0+, Safari 
  37.  xmlHttp=new XMLHttpRequest(); 
  38.  } 
  39. catch (e) 
  40.  { 
  41.  // Internet Explorer 
  42.  try 
  43.   { 
  44.   xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); 
  45.   } 
  46.  catch (e) 
  47.   { 
  48.   xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); 
  49.   } 
  50.  } 
  51. return xmlHttp; 
  52. } 

php操作代码如下:

  1. <?php 
  2. $q=$_GET["q"]; 
  3. $q = urldecode($q); 
  4. if (strlen($q) > 0) 
  5. { 
  6.   $conn = @mysql_connect("localhost","root","1010") or die ("MySql连接错误"); 
  7.   mysql_select_db("xin",$conn); 
  8.   mysql_query("set names 'utf8'"); 
  9.    
  10.   $sql = "SELECT username FROM message WHERE username = '$q'"; 
  11.   $query = mysql_query($sql); 
  12.   @$row = mysql_fetch_array($query); 
  13.    
  14.   if(!emptyempty($row['username'])) 
  15.   {//开源软件:phpfensi.com 
  16.    $response = "<font color=red>已经被注册!</font>"; 
  17.   }else 
  18.   { 
  19.    $response = "<font color=blue>恭喜!可以注册!</font>"; 
  20.   } 
  21.    
  22.   echo $response; 
  23. } 
  24. ?> 

最后再给出数据库代码:

  1. DROP DATABASE IF EXISTS `xin`; 
  2. CREATE DATABASE `xin` /*!40100 DEFAULT CHARACTER SET utf8 */; 
  3. USE `xin`; 
  4.  
  5. CREATE TABLE `message` ( 
  6.   `id` int(11) NOT NULL auto_increment, 
  7.   `username` varchar(20) default NULL, 
  8.   PRIMARY KEY  (`id`) 
  9. ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

Tags: php+ajax php注册验证

分享到: