首页 > 代码库 > PHP的ajax

PHP的ajax

代码如下

先建立一个表单

 

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<script type="text/javascript" src="http://www.mamicode.com/ajax.js"></script>
</head>

<body>

<form action="" >
用户名: <input type="text" name="user" id="" onblur="sendParam(this.value)"/>
<span style="color: red;font-size: 14px" id="tishi"></span>
<br/>
密 码: <input type="password" name="mima"/> <br/>

<input type="submit" value="http://www.mamicode.com/提交" name="submit"/>
</form>
</body>

</html>

 

然后

数据库的基本语言   

<?php
if(isset($_GET[‘user‘])){
$user = $_GET[‘user‘];

$conn = mysql_connect("localhost","root","") or die("数据库连接失败".mysql_error());
mysql_select_db("test");
mysql_query("set names ‘utf8‘");

$sql = "select count(*) from bbs where userName=‘$user‘";

$result = mysql_query($sql);
$row = mysql_fetch_row($result);

if($row[0]){
echo "该用户名已经被注册";
}else{
echo "该用户名还没有被使用过,可以注册";
}
}
?>

 

最后AJAX

 


var xmlHttp;
function getXmlHttp(){
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("MICROSOFT.XMLHTTP");
}else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}

function sendParam(url){
getXmlHttp();

xmlHttp.open("GET","check.php?user="+url,true);
// setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = getTxt;
xmlHttp.send(null);
}
function getTxt(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
var sp = document.getElementById("tishi");
sp.innerHTML = xmlHttp.responseText;
}
}
}