用ajax +bootstrap实现前后端交互之 注册,登录,查询数据,修改和删除数据(css自行下载)

1.1 注册页面 register.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>注册</title>
		<link rel="stylesheet" href="../css/bootstrap.min.css">
		<style>
			#register{width: 400px; margin: 150px auto}
			#alert_info{margin: 2px; padding: 2px;text-align: center; margin-bottom: 10px; display: none}
		</style>
		<script src = '../ajax.js'></script>
		<script>
			window.onload = function(){
				var oBtn = document.getElementById("btn1");
				var oAlert = document.getElementById("alert_info");
				var aInputs = document.getElementsByTagName("input");

				oBtn.onclick = function(){
					$ajax({
						method: "post",
						url: "register.php",
						data: {
							username: aInputs[0].value,
							password: aInputs[1].value,
							addTime: new Date().getTime()
						},
						success: function(result){
							var obj = JSON.parse(result);
							if(obj.code){
								oAlert.className = 'alert alert-danger';
							}else{
								oAlert.className = 'alert alert-success';
								setTimeout(function(){
									location.href = "login.html";
								}, 1000);
							}
							oAlert.style.display = 'block';
							oAlert.innerHTML = obj.message;
						},
						error: function(msg){
							alert(msg);
						}
					})
				}
			}

		</script>
	</head>
	<body>
		<div class = 'container'>
			<div class = 'panel panel-primary' id = 'register'>
				<div class = 'panel-heading'>
					注册
				</div>
				<div class = 'panel-body'>
					<div class = 'form-group'>
						<label for="username">用户名:</label>
						<input type="text" name = 'username' class = 'form-control'>
					</div>
					<div class = 'form-group'>
						<label for="password">密码:</label>
						<input type="text" name = 'password' class = 'form-control'>
					</div>
					<div id = 'alert_info' class = 'alert alert-danger'>xxxxx</div>
					<a href="login.html">马上登录</a>
					<button id = 'btn1' class = 'btn btn-primary pull-right'>注册</button>
				</div>
			</div>
		</div>
	</body>
</html>

1.2 register.php

<?php 
	header("Content-type:text/html;charset=utf-8");
	//统一发返回格式
	$responseData = array("code" => 0, "message" => "");
	//取出传过来的数据
	$username = $_POST["username"];
	$password = $_POST["password"];
	$addTime = $_POST["addTime"];

	//简单的验证
	if(!$username){
		$responseData["code"] = 1;
		$responseData["message"] = "用户名不能为空";
		echo json_encode($responseData);
		exit;
	}
	if(!$password){
		$responseData["code"] = 2;
		$responseData["message"] = "密码不能为空";
		echo json_encode($responseData);
		exit;
	}
	
	//链接数据库
	$link = mysql_connect("localhost", "root", "root");

	//2、判断是否连接成功
	if(!$link){
		echo "链接失败";
		$responseData["code"] = 3;
		$responseData["message"] = "数据库链接失败";
		echo json_encode($responseData);
		exit; //终止后续所有的代码
	}

	//3、设置字符集
	mysql_set_charset('utf8');

	//4、选择数据库
	mysql_select_db("yyy");
	//5、准备sql  验证用户名是否重名
	$sql1 = "SELECT * FROM users WHERE username='{$username}'";

	//6、发送sql语句
	$res = mysql_query($sql1);
	//7、取出一行数据
	$row = mysql_fetch_assoc($res);
	
	if($row){
		//用户名重名
		$responseData["code"] = 4;
		$responseData["message"] = "用户已存在";
		echo json_encode($responseData);
		exit;
	}
	//md5加密
	// $str = md5(md5(md5($password)."xxx")."yyy");

	//准备sql将数据插入到数据库中
	$sql2 = "INSERT INTO users(username,password,create_time) VALUES('{$username}','{$password}',{$addTime})";
	
	//返回布尔值
	$res = mysql_query($sql2);
	if(!$res){
		$responseData["code"] = 5;
		$responseData["message"] = "注册失败";
		echo json_encode($responseData);
	}else{
		$responseData["message"] = "注册成功";
		echo json_encode($responseData);
	}

	mysql_close($link);
 ?>

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.1 登录页面 login.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>登录</title>
		<link rel="stylesheet" href="../css/bootstrap.min.css">
		<style>
			#register{width: 400px; margin: 150px auto}
			#alert_info{margin: 2px; padding: 2px;text-align: center; margin-bottom: 10px; display: none}
		</style>
		<script src = '../ajax.js'></script>
		<script>
			window.onload = function(){
				var oBtn = document.getElementById("btn1");
				var oAlert = document.getElementById("alert_info");
				var aInputs = document.getElementsByTagName("input");

				oBtn.onclick = function(){
					$ajax({
						method: "post",
						url: "login.php",
						data: {
							username: aInputs[0].value,
							password: aInputs[1].value
						},
						success: function(result){
							var obj = JSON.parse(result);
							if(obj.code){
								oAlert.className = 'alert alert-danger';
							}else{
								oAlert.className = 'alert alert-success';
								setTimeout(function(){
									location.href = "userlist.html";
								}, 2000);
							}
							oAlert.style.display = 'block';
							oAlert.innerHTML = obj.message;
						},
						error: function(msg){
							alert(msg);
						}
					})
				}
			}

		</script>
	</head>
	<body>
		<div class = 'container'>
			<div class = 'panel panel-primary' id = 'register'>
				<div class = 'panel-heading'>
					登录
				</div>
				<div class = 'panel-body'>
					<div class = 'form-group'>
						<label for="username">用户名:</label>
						<input type="text" name = 'username' class = 'form-control'>
					</div>
					<div class = 'form-group'>
						<label for="password">密码:</label>
						<input type="text" name = 'password' class = 'form-control'>
					</div>
					<div id = 'alert_info' class = 'alert alert-danger'>xxxxx</div>
					<a href="register.html">马上注册</a>
					<button id = 'btn1' class = 'btn btn-primary pull-right'>登录</button>
				</div>
			</div>
		</div>
	</body>
</html>

2.1 登录页面 login.php

<?php 
	header("Content-type:text/html;charset=utf-8");
	//统一发返回格式
	$responseData = array("code" => 0, "message" => "");
	//取出传过来的数据
	$username = $_POST["username"];
	$password = $_POST["password"];

	//简单的验证
	if(!$username){
		$responseData["code"] = 1;
		$responseData["message"] = "用户名不能为空";
		echo json_encode($responseData);
		exit;
	}
	if(!$password){
		$responseData["code"] = 2;
		$responseData["message"] = "密码不能为空";
		echo json_encode($responseData);
		exit;
	}
	
	//链接数据库
	$link = mysql_connect("localhost", "root", "root");

	//2、判断是否连接成功
	if(!$link){
		echo "链接失败";
		$responseData["code"] = 3;
		$responseData["message"] = "数据库链接失败";
		echo json_encode($responseData);
		exit; //终止后续所有的代码
	}

	//3、设置字符集
	mysql_set_charset("utf8");

	//4、选择数据库
    mysql_select_db("yyy");

    //md5加密
    //  $str = md5(md5(md5($password)."xxx")."yyy");
     
    //5、登录
    $sql1 = "select * from users where username = '{$username}' and password='{$password}'";

	 //6、发送sql语句
	$res = mysql_query($sql1);
	//7、取出一行数据
	$row = mysql_fetch_assoc($res);
	
	if(!$row){
		$responseData["code"] = 4;
		$responseData["message"] = "用户名或者密码错误";
		echo json_encode($responseData);
	}else{
        $responseData["message"] = "登陆成功";
		echo json_encode($responseData);
    }
	mysql_close($link);
 ?>

在这里插入图片描述

在这里插入图片描述

3.1 获取用户列表页面 userlist.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>Document</title>
		<link rel="stylesheet" href="../css/bootstrap.min.css">
		<link rel="stylesheet" href="../css/buttons.css">
		<script src = '../ajax.js'></script>
		<script src = '../tool.js'></script>
		<script>
			window.onload = function(){
				var oBtn = document.getElementById("btn1");
				var oT1 = document.getElementById("t1");

				oBtn.onclick = function(){
					$ajax({
						method: "get",
						url: "userlist.php",
						success: function(result){
							var arr = JSON.parse(result);
							//通过循环创建节点添加到页面上
							var str = ``;
							for(var i = 0; i < arr.length; i++){
								str += `<tr>
									<td>${arr[i].id}</td>
									<td>${arr[i].username}</td>
									<td>${arr[i].password}</td>
									<td>${showTime(Number(arr[i].create_time))}</td>
									<td id = '${arr[i].id}'>
										<a href = "#">删除</a>
										/
										<a href = "updateStudents.html?id=${arr[i].id}">修改</a>
									</td>
								</tr>`;
							}

							oT1.innerHTML = str;
						},
						error: function(msg){
							alert(msg);
						}
					})
				}


				//给所有的删除按钮和修改按钮添加点击
				oT1.onclick = function(ev){
					var e = ev || window.event;
					var target = e.target || window.event.srcElement;
					if(target.nodeName.toLowerCase() == "a" && target.innerHTML == "删除"){
						//拿到当前要删除的数据的id
						var id = target.parentNode.id;
						$ajax({
								method: "get",
								url: "deleteStudents.php",
								data: {
									id: id
								},
								success: function(result){
									var obj = JSON.parse(result);
									if(!obj.code){
										oT1.removeChild(target.parentNode.parentNode);
									}else{
										alert(obj.message);
									}
								},
								error: function(msg){
									alert(msg)
								}
							})



						return false;
					}
				}
			}
		</script>
	</head>
	<body>
		<div class = 'container'>
			<div class = 'panel panel-primary'>
				<div class = 'panel-heading'>
					<h2>获取用户列表</h2>
				</div>
				<div class = 'panel-body'>
					<button id = 'btn1' class = 'button button-glow button-rounded button-raised button-primary'>获取用户数据</button>
					<br><br>
					<table class = 'table table-bordered  table-hover'>
						<thead>
							<tr>
								<th>用户id</th>
								<th>用户名</th>
								<th>密码</th>
								<th>注册日期</th>
								<th>操作</th>
							</tr>
						</thead>
						<tbody id = 't1'>
							
						</tbody>
					</table>
				</div>
				<div class = 'panel-footer'></div>
			</div>
		</div>
	</body>
</html>

3.2 获取用户列表页面 userlist.php

<?php 
	header("Content-type:text/html;charset=utf-8");
	//链接数据库
	$link = mysql_connect("localhost", "root", "root");

	//2、判断是否连接成功
	if(!$link){
		echo "数据库链接失败";
		exit; //终止后续所有的代码
	}

	//3、设置字符集
	mysql_set_charset("utf8");

	//4、选择数据库
	mysql_select_db("yyy");

	//5、准备sql
	$sql = "SELECT * FROM users";

	$res = mysql_query($sql);

	$arr = array();

	while($row = mysql_fetch_assoc($res)){
		array_push($arr, $row);
	}

	echo json_encode($arr);

	mysql_close($link);
 ?>

在这里插入图片描述

4. 删除用户页面 deleteStudents.php

<?php 
	//删除操作
	header("Content-type:text/html;charset=utf-8");
	//统一发返回格式
	$responseData = array("code" => 0, "message" => "");

	//删除的数据
	$id = $_GET['id'];

	//1、链接数据库
	$link = mysql_connect("localhost", "root", "root");
	//2、判断是否链接成功
	if(!$link){
		$responseData['code'] = 1;
		$responseData['message'] = "数据库链接失败";
		//返回到前台页面你
		echo json_encode($responseData);
		exit;
	}
	//3、设置字符集
	mysql_set_charset("utf8");

	//4、选择数据库
	mysql_select_db("yyy");

	//5、准备sql语句,通过id删除
	$sql = "DELETE FROM users WHERE id={$id}";

	$res = mysql_query($sql);

	if(!$res){
		$responseData['code'] = 2;
		$responseData['message'] = "删除用户数据失败";
		//返回到前台页面你
		echo json_encode($responseData);
	}else{
		$responseData['message'] = "删除用户数据成功";
		//返回到前台页面你
		echo json_encode($responseData);
	}

	mysql_close($link);

 ?>

在这里插入图片描述

5.1 修改用户页面 updateStudents.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>注册</title>
		<link rel="stylesheet" href="../css/bootstrap.min.css">
		<style>
			#update{width: 400px; margin: 150px auto}
			#alert_info{margin: 2px; padding: 2px;text-align: center; margin-bottom: 10px; display: none}
		</style>
		<script src = '../ajax.js'></script>
		<script>
			window.onload = function(){
				var oBtn = document.getElementById("btn1");
				var oAlert = document.getElementById("alert_info");
				var aInputs = document.getElementsByTagName("input");

				//给提交按钮添加点击
				oBtn.onclick = function(){
					$ajax({
						method: "post",
						url: 'submitStudents.php',
						data: {
							username: aInputs[0].value,
							password: aInputs[1].value,
							id: aInputs[2].value
						},
						success: function(result){
							var obj = JSON.parse(result);
							if(obj.code){
								oAlert.className = 'alert alert-danger';
							}else{
								oAlert.className = 'alert alert-success';
								setTimeout(function(){
									location.href = "userlist.html";
								}, 2000);
							}
							oAlert.style.display = 'block';
							oAlert.innerHTML = obj.message;
						},
						error: function(msg){
							alert(msg);
						}
					})
				}



				var id = valueByName(location.search, "id");

				//发送id到后台php的页面
				$ajax({
					method: "get",
					url: "updateStudents.php",
					data: {
						id: id
					},
					success: function(result){
						var obj = JSON.parse(result);
						if(!obj.code){
							var row = JSON.parse(obj.message);
							aInputs[0].value = row.username;
							aInputs[1].value = row.password;
							aInputs[2].value = row.id;
						}
					},
					error: function(msg){
						alert(msg);
					}
				})

			}




			//name1=value1&name2=value2&name3=value3 提取id值的函数
			function valueByName(search, name){
				var start = search.indexOf(name + "=");
				if(start == -1){
					return null;
				}else{
					var end = search.indexOf("&", start);
					if(end == -1){
						end = search.length;
					}

					//提取出想要键值对 name=value
					var str = search.substring(start, end);
					var arr = str.split("=");
					return arr[1];
				}

			}

		</script>
	</head>
	<body>
		<div class = 'container'>
			<div class = 'panel panel-primary' id = 'update'>
				<div class = 'panel-heading'>
					修改用户数据
				</div>
				<div class = 'panel-body'>
					<div class = 'form-group'>
						<label for="username">用户名:</label>
						<input type="text" name = 'username' class = 'form-control'>
					</div>
					<div class = 'form-group'>
						<label for="password">密码:</label>
						<input type="text" name = 'password' class = 'form-control'>
					</div>
					<div class = 'form-group'>
					<!-- 隐藏表单 -->
						<input type="hidden" name = 'id' class = 'form-control'>
					</div>
					<div id = 'alert_info' class = 'alert alert-danger'>xxxxx</div>
					<a href="userlist.html">查看用户列表</a>
					<button id = 'btn1' class = 'btn btn-primary pull-right'>提交</button>
				</div>
			</div>
		</div>
	</body>
</html>

5.2 修改用户页面 updateStudents.php

<?php 
	header("Content-type:text/html;charset=utf-8");
	//统一发返回格式
	$responseData = array("code" => 0, "message" => "");

	$id = $_GET['id'];

	if(!$id){
		$responseData["code"] = 1;
		$responseData["message"] = "没有要修改数据";
		echo json_encode($responseData);
		exit; //终止后续所有的代码
	}

	//链接数据库
	$link = mysql_connect("localhost", "root", "root");

	//2、判断是否连接成功
	if(!$link){
		
		$responseData["code"] = 2;
		$responseData["message"] = "数据库链接失败";
		echo json_encode($responseData);
		exit; //终止后续所有的代码
	}

	//3、设置字符集
	mysql_set_charset("utf8");

	//4、选择数据库
	mysql_select_db("yyy");

	//5、准备sql从查找数据
	$sql = "SELECT * FROM users WHERE id={$id}";

	$res = mysql_query($sql);

	$row = mysql_fetch_assoc($res);

	if(!$row){
		$responseData["code"] = 3;
		$responseData["message"] = "修改的数据不存在";
		echo json_encode($responseData);
	}else{
		$responseData["message"] = json_encode($row);
		echo json_encode($responseData);
	}

	mysql_close($link);

 ?>

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

6 修改用户的判断 submitStudents.php

<?php 
	header("Content-type:text/html;charset=utf-8");
	//统一发返回格式
	$responseData = array("code" => 0, "message" => "");
	//取出传过来的数据
	$username = $_POST["username"];
	$password = $_POST['password'];
	$id = $_POST["id"];

	//简单的验证
	if(!$username){
		$responseData["code"] = 1;
		$responseData["message"] = "用户名不能为空";
		echo json_encode($responseData);
		exit;
	}
	if(!$password){
		$responseData["code"] = 2;
		$responseData["message"] = "密码不能为空";
		echo json_encode($responseData);
		exit;
	}
	if(!$id){
		$responseData["code"] = 3;
		$responseData["message"] = "修改的用户不存在";
		echo json_encode($responseData);
		exit;
	}
	
	
	//链接数据库
	$link = mysql_connect("localhost", "root", "root");

	//2、判断是否连接成功
	if(!$link){
		
		$responseData["code"] = 3;
		$responseData["message"] = "数据库链接失败";
		echo json_encode($responseData);
		exit; //终止后续所有的代码
	}

	//3、设置字符集
	mysql_set_charset("utf8");

	//4、选择数据库
	mysql_select_db("yyy");


	//5、判断用户名是否重名
	$sql = "SELECT * FROM users WHERE username='{$username}' AND id!={$id}";

	$res = mysql_query($sql);
	$row = mysql_fetch_assoc($res);
	if($row){
		$responseData["code"] = 4;
		$responseData["message"] = "用户名重名,不能修改";
		echo json_encode($responseData);
		exit; //终止后续所有的代码
	}
	//md5加密
	// $str = md5(md5(md5($password)."xxx")."yyy");
	
	$sql2 = "UPDATE users SET username='{$username}',password='{$password}' WHERE id={$id}";

	$res2 = mysql_query($sql2);
	if($res2){
		$responseData["message"] = "修改成功";
		echo json_encode($responseData);
	}else{
		$responseData["code"] = 5;
		$responseData["message"] = "用户名修改失败,请重试";
		echo json_encode($responseData);
		exit; //终止后续所有的代码
	}
	mysql_close($link);



 ?>

在这里插入图片描述

ajax.js

function $ajax({method = "get",url,data,success,error}){
    //1、创建ajax对象
    var xhr = null;
        try{
            xhr = new XMLHttpRequest();
        }catch(error){
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
    //判断如果数据存在
    if(data){
        data = querystring(data);
    }
    if(method == "get" && data){
        url += "?" + data;
    }
    xhr.open(method,url,true);
            
    if(method == "get"){
    xhr.send();
    }else{
    //必须在send方法之前,去设置请求的格式
    xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    xhr.send(data);
    }
    //4、等待数据响应
           
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
        //判断本次下载的状态码都是多少
            if(xhr.status == 200){
                /*
                如何去处理数据不确定
                回调函数,
                */
                if(success){
                    success(xhr.responseText);
                }
            }else{
                if(error){
                    error("Error:" + xhr.status);
                }
              }
        }
    }
}
//转成字符串函数
function querystring(obj){
    var str ="";
    for (var attr in obj) {
       str += attr + "=" + obj[attr] +"&";
    }
   return  str.substring(0,str.length - 1)
}
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值