您的位置:首页 > 其它

利用Ajax判断注册用户名是否已被注册

2016-03-28 00:00 417 查看
摘要: 一个让你理解ajax工作原理的例子:一个前端页面的简单的ajax结合后台数据库查询来实现用户名是否已经被注册的文字提示

HTML代码部分:

文件名为:post.html

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="post.php" method="post">
<table>
<tr>
<td>用户名</td>
<td><input type="text" name="user_name" id="user"><span></span></td>
</tr>
<tr>
<td>密 码</td>
<td><input type="password" name="user_pwd"></td>
</tr>
<tr>
<td colspan="2"><input type="submit"></td>
</tr>
</table>
</form>
</body>
<script>
var user = document.getElementById('user');

user.onblur=function(){
var user_name = user.value;
var ajax = false;

//1.根据浏览器的不同,使用不同的方法创建对象
if(window.ActiveXObject){
ajax = new ActiveXObject('Microsoft.XMLHTTP');
}else if(window.XMLHttpRequest){
ajax = new XMLHttpRequest();
}

//2.创建请求
ajax.open('post','post.php',true);

//3.发送请求,send里面的参数只能通过post方法发送
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
// ajax.send();当方式为get的时候用这个
ajax.send('user='+user_name);//当方式为post的时候用这个

//4.判断请求的状态和请求结果
ajax.onreadystatechange=function(){
if(ajax.readyState==4 && ajax.status==200){
var message = ajax.responseText;
console.log(message);
if(message==1){
user.nextSibling.innerHTML='<font color="red">×,不可以注册</font>';
}else{
user.nextSibling.innerHTML='<font color="green">√,可以注册</font>';
}
}
}

}
</script>
</html>

PHP代码部分:

文件名为post.php

<?php
header("Content-Type:text/html;charset:utf-8");
include_once('mysql_class.php');

$mysql = new mysql('localhost','root','','wdopro','utf8');
$user_name = $_POST['user_name'];
$sql = 'SELECT * FROM wdo_admin WHERE admin_name = "'.$user_name.'"';
$result = $mysql->get_one($sql);
if($result){
echo 1;
}else{
echo 0;
}

?>

另外在根目录下添加一个定义好的类(也就是php文件中引入的类)

mysql_class.php

关于这个类可以看我之前写的博客。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息