ajax验证用户名
index_do.php
<?php
header("Content-Type:text/html;charset=utf-8");
header("Cache-Control:no-cache");
$username=$_POST['username'];
$info="";
if ($username=='admin'){
$info='{"name":"owen","age":"24","sex":"man"}';
}else {
$info='{"name":"nancy","age":"23","sex":"woman"}';
}
echo $info;
?>
index.php
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>ajax</title>
<script type="text/javascript" src="ajax.js"></script>
<script type="text/javascript">
function $(id){
return document.getElementById(id);
}
function checkName(){
var http_request=createAjax();
http_request.onreadystatechange=function(){
if(http_request.readyState==4 && http_request.status==200){
var notice=http_request.responseText;
var notice_obj=eval("("+notice+")");
$("notice").innerHTML=notice_obj.name;
} // www.jbxue.com
}
var data="username="+$("username").value+"&mytime="+new Date();
var url="index_do.php";
http_request.open("post",url,true);
http_request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
http_request.send(data);
}
</script>
</head>
<body>
Please enter your username:<input type="text" name="username" id="username" onChange="checkName();" />
<span id="notice"></span>
</body>
</html>
这里用到了eval()函数,将json格式的数据库转换成对象。这样就可以很方便的取出数据。对象属性对应属性值。
var notice=http_request.responseText;
var notice_obj=eval("("+notice+")");