首先要了解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>";
}