• 我们应该有新到生活,为我们未经生活过到的。

Ajax实现用户名验证

基于AJAX的注册很多,网上大多用GET请求,我用POST实现了一下。

function CheckUser(){
	var xmlHttp;
	var UserName=document.regForm.userName.value;
	if(UserName==""||UserName==null){
		alert("input word");
	}
	else{
		if(window.ActiveXObject){
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}else if(window.XMLHttpRequest){
			xmlHttp = new XMLHttpRequest();
		}
		xmlHttp.onreadystatechange=function(){
			if(xmlHttp.readyState ==4){
				if(xmlHttp.status==200){
					var response=xmlHttp.responseText;
					alert(response );
				}
			}
		}
		xmlHttp.open("post", "/phpstudy/reg.php",true);
		xmlHttp.send(UserName);
	}
}
<form name="regForm">
	<fieldset>
		<legend>用户注册</legend>
		<label>name</label>
		<input name="userName" onblur="CheckUser()" type="text">
		<label>password</label>
	</fieldset>
</form>
$conn=mysql_connect("localhost","root","root")
or die('Could not connect: ' . mysql_error());	

$db_link=mysql_select_db("phpstudy",$conn)
or die('Could not select database');	

$sql="select * from user where name='$HTTP_RAW_POST_DATA'";
$result=mysql_query($sql,$conn);
$info=mysql_fetch_array($result);
if($info){
	echo "用户已被占用";
}
else{
	echo "可以注册";
}

用POST方法遇到的问题
服务器对POST请求和提交WEB表单的请求处理有差异,因此有两种思路来解决
1.用XMLHttpRequest模拟表单提交
首先将Content-Type头部信息设置为application/x-www-from-urlencoded,也就是表单体提交时的内容类型
其次是以适当的格式创建一个字符串

2.服务器端用$HTTP_RAW_POST_DATA来接收数据
由于PHP默认只识别application/x-www.form-urlencoded标准的数据类型,因此,对型如text/xml的内容无法解析为$_POST数组,故保留原型,交给$GLOBALS['HTTP_RAW_POST_DATA'] 来接收

Give lefter a comment

Your comment