AJAX 检测用户名是否存在

首先要了解AJAX的工作原理

AJAX工作原理:

1:HTML页面(触发)——->javascript脚本(执行)—–>
PHP文件(反应)——–>javascript脚本(返回)—–>HTML页面(展示)

验证用户名源码:

index.html

<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Strict//EN' 'http://www.w3.org/TR/html4/strict.dtd'>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<title>insert into title</title>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>
       <form method="get" name="myform" enctype="multipart/form-data">
            用户:<input type="text" name="user" id="user" onblur="showName(this.value)"><br>
               <div name="txtint" id="txtint" style="width:200px;height:20px;"></div>
            密码:<input type="password" name="pass" id="pass" style="width:149px;"><br>
       </form>

</body>
</html>

ajax.JS

var xmlHttp;

function GetXmlHttpObject(){
    var xmlHttp=null;
    try{
        xmlHttp=new XMLHttpRequest();
    }catch(e){
        try{
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }catch(e){
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }

    return xmlHttp;
}

function showName(str){
    if(str.length==0){
        document.getElementById("txtint").innerHTML="用户名不能为空!";
        return;
    }

    xmlHttp=GetXmlHttpObject()
    if(xmlHttp==null){
        alert("Browser does not support HTTP Request");
        return;
    }

    var url="index.php"
        url=url+"?q="+str
        url=url+"&uid="+Math.random()
        xmlHttp.open("GET",url,true);
        xmlHttp.onreadystatechange=statechanged
        xmlHttp.send(null)
}

function statechanged(){    
    if(xmlHttp.readyState==4||xmlHttp.readyState=="complete"){
        document.getElementById("txtint").innerHTML=xmlHttp.responseText
    }
}

index.php

  header("content-type:text/html;charset=utf-8");  

  $q=$_GET["q"];
  $conn=mysql_connect("localhost","root","admin")or die(mysql_error());
  mysql_select_db("test",$conn)or die(mysql_error());
  mysql_query("SELECT * FROM UTF8");

  $sql="SELECT * FROM testuser where Firstname='".$q."'";
  $result=mysql_query($sql,$conn);

  if(!is_array(mysql_fetch_row($result))){
         echo "<font color='green'>用户名可以使用</font>";

  }else{
         echo "<font color='red'>用户名已经存在</font>";
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值