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


<!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>

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

<?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."】没有被注册!";
}
?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值