您的位置:首页 > 编程语言 > PHP开发

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

2013-12-03 14:14 267 查看
Java代码  


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  

<html xmlns="http://www.w3.org/1999/xhtml">  

<head>  

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />  

<title>检测用户名是否存在</title>  

</head>  

<body>  

<script language="javascript">  

//搭建ajax开发框架  

var http_request=false;  

function createRequest(url){  

    http_request=false;  

    if(window.XMLHttpRequest){//Mozilla等浏览器  

        http_request=new XMLHttpRequest();  

        if(http_request.overrideMimeType){  

        /** 

        *针对某些特定的版本的mozilla浏览器的bug进行修正. 

        *如果来自服务器的响应没有xml mime-type头部,则一些版本的Mozilla浏览器不能正常运作 

        *针对这种情况,overrideMimeType("text/xml")语句将覆盖发送给服务器的头部,强制test/xml作为mime-type 

        */  

            http_request.overrideMimeType("text/xml");  

        }  

    }else if(window.ActiveXObject){  

        try{  

            http_request=new ActiveXObject("Msxml2.XMLHTTP");  

        }catch(e){  

            try{  

                http_request=new ActiveXObject("Microsoft.XMLHTTP");  

            }catch(e){}  

        }  

    }  

    if(!http_request){  

        alert("不能创建XMLHTTP实例!");  

        return false;  

    }  

    http_request.onreadystatechange=alertContents;//指定响应方法  

    //发出HTTP请求  

    http_request.open("GET",url,true);  

    http_request.send(null);  

}  

function alertContents(){  

    if(http_request.readyState==4){  

        if(http_request.status==200){  

            alert(http_request.responseText);  

        }else{  

            alert("您请求的页面发现错误");  

        }  

    }  

}  

</script>  

<script language="javascript">  

function checkName(){  

    var username=form1.username.value;  

    if(username==""){  

        window.alert("请填写用户名!");  

        form1.username.focus();  

        return false;  

    }else{  

        createRequest('checkname.php?username='+username+'&nocache='+new Date().getTime());//必须添加清除缓存的代码,否则程序将不能正确检测用户名是否被占用  

    }  

}  

</script>  

<form id="form1">  

<input type="text" id="username" name="username"/>  

<a href="#" onclick="checkName();">[检测用户名]</a>  

</form>  

</body>  

</html>  

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

Java代码  


<?php   

$link=mysql_connect("localhost","root","root");  

mysql_select_db("db_database23",$link);  

//ajax中先用encodeURIComponent对要提交的中文进行编码  

$GB2312string=iconv('UTF-8','gb2312//IGNORE',$RequestAjaxString);  

mysql_query("set names gb2312");  

$username=$_GET['username'];  

$sql=mysql_query("select * from tb_user where name='".$username."'");  

$info=mysql_fetch_array($sql);  

header('Content-type:text/html;charset=GB2312');//指定发送数据的编码格式为GB2312  

if($info){  

    echo "很抱歉!用户名【".$username."】已经被注册!";  

}else{  

    echo "祝贺您!用户名【".$username."】没有被注册!";  

}  

?>  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: