您的位置:首页 > 其它

AJAX 检测用户名是否存在

2015-10-19 15:52 447 查看

首先要了解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>";
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: