首页 > 代码库 > text2——ajax基础

text2——ajax基础

用ajax进行验证:

 HTML代码:

          

<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=""/> <br/>

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

</html>

 

php代码:

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

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

$sql = "select count(*) from users where sname=‘$user‘";

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

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

ajax代码(js):

 

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;
}
}
}