php中使用ajax检测用户名(举例)_xml



    1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
    2. <html xmlns="http://www.w3.org/1999/xhtml">  
    3. <head>  
    4. <meta http-equiv="Content-Type" content="text/html; charset=gb2312"
    5. <title>检测用户名是否存在</title>  
    6. </head>  
    7. <body>  
    8. <script language="javascript">  
    9. //搭建ajax开发框架
    10. var http_request=false;  
    11. function createRequest(url){  
    12. false;  
    13. if(window.XMLHttpRequest){//Mozilla等浏览器
    14. new
    15. if(http_request.overrideMimeType){  
    16. /**
    17.         *针对某些特定的版本的mozilla浏览器的bug进行修正.
    18.         *如果来自服务器的响应没有xml mime-type头部,则一些版本的Mozilla浏览器不能正常运作
    19.         *针对这种情况,overrideMimeType("text/xml")语句将覆盖发送给服务器的头部,强制test/xml作为mime-type
    20.         */
    21. "text/xml");  
    22.         }  
    23. else if(window.ActiveXObject){  
    24. try{  
    25. new ActiveXObject("Msxml2.XMLHTTP");  
    26. catch(e){  
    27. try{  
    28. new ActiveXObject("Microsoft.XMLHTTP");  
    29. catch(e){}  
    30.         }  
    31.     }  
    32. if(!http_request){  
    33. "不能创建XMLHTTP实例!");  
    34. return false;  
    35.     }  
    36. //指定响应方法
    37. //发出HTTP请求
    38. "GET",url,true);  
    39. null);  
    40. }  
    41. function alertContents(){  
    42. if(http_request.readyState==4){  
    43. if(http_request.status==200){  
    44.             alert(http_request.responseText);  
    45. else{  
    46. "您请求的页面发现错误");  
    47.         }  
    48.     }  
    49. }  
    50. </script>  
    51. <script language="javascript">  
    52. function checkName(){  
    53.     var username=form1.username.value;  
    54. if(username==""){  
    55. "请填写用户名!");  
    56.         form1.username.focus();  
    57. return false;  
    58. else{  
    59. 'checkname.php?username='+username+'&nocache='+new Date().getTime());//必须添加清除缓存的代码,否则程序将不能正确检测用户名是否被占用
    60.     }  
    61. }  
    62. </script>  
    63. <form id="form1">  
    64. <input type="text" id="username" name="username"/>  
    65. <a href="#" οnclick="checkName();">[检测用户名]</a>  
    66. </form>  
    67. </body>  
    68. </html>


    与数据库交互的处理页面: 


    php中使用ajax检测用户名(举例)_xml



    1. <?php   
    2. $link=mysql_connect("localhost","root","root");  
    3. mysql_select_db("db_database23",$link);  
    4. //ajax中先用encodeURIComponent对要提交的中文进行编码
    5. $GB2312string=iconv('UTF-8','gb2312//IGNORE',$RequestAjaxString);  
    6. mysql_query("set names gb2312");  
    7. $username=$_GET['username'];  
    8. $sql=mysql_query("select * from tb_user where name='".$username."'");  
    9. $info=mysql_fetch_array($sql);  
    10. header('Content-type:text/html;charset=GB2312');//指定发送数据的编码格式为GB2312
    11. if($info){  
    12. "很抱歉!用户名【".$username."】已经被注册!";  
    13. }else{  
    14. "祝贺您!用户名【".$username."】没有被注册!";  
    15. }  
    16. ?>