摘要:<!DOCTYPE html> <html lang = "en"> <head> <meta charset = "UTF-8"> <ti
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>Login</title>
<style>
* {
padding: 0;
margin: 0;
}
.box {
margin: 20px auto;
width: 260px;
text-align: center;
}
form {
margin: 20px auto;
overflow: hidden;
}
form p {
margin: 10px 0;
height: 30px;
line-height: 30px;
}
input {
height: 25px;
}
button {
width: 100px;
height: 35px;
}
.tips {
float: left;
text-align: right;
}
.input {
float: left;
text-align: left;
}
#prompt {
color: red;
}
</style>
</head>
<body>
<div class = "box">
<h3>请登录</h3>
<form>
<div class = "tips">
<p><label for = "username">用户名:</label></p>
<p><label for = "password">密码:</label></p>
</div>
<div class = "input">
<p><input type = "text" name = "username" id = "username"></p>
<p><input type = "password" name = "password" id = "password"></p>
<p>
<button type = "button">登录</button>
</p>
</div>
</form>
<p id = "prompt"></p>
</div>
</body>
<script>
let btn = document.getElementsByTagName('button')[0];
btn.onclick = function () {
// 创建xhr对象
let xhr = new XMLHttpRequest();
// 监听响应状态 -- 每当readyState改变时,就会触发onreadystatechange事件。
xhr.onreadystatechange = function () {
// readyState为4时:请求已完成,且响应已就绪
if (xhr.readyState === 4) {
// status的值,200:‘OK';404:未找到页面
if (xhr.status === 200) {
let prompt = document.getElementById('prompt');
let json = JSON.parse(xhr.responseText);
// console.log(json);
prompt.innerHTML = json['msg'];
setTimeout(function () {
if (json['status'] === 1) {
location.href = 'admin.php';
} else if (json['status'] === 0) {
document.getElementsByName('username')[0].value = '';
document.getElementsByName('password')[0].value = '';
prompt.innerHTML = '';
}
}, 3000);
}
}
};
// 设置请求参数
xhr.open('post', 'check.php', true);
// 设置头信息,将内容类型设置为表单提交方式
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// 发送请求数据
let date = {
username: document.getElementsByName('username')[0].value,
password: document.getElementsByName('password')[0].value
};
let dateJson = JSON.stringify(date);
xhr.send('date=' + dateJson);
};
</script>
</html><?php
// 用于验证的数据
$db = [
[
'username' => 'admin',
'password' => '000000',
],
[
'username' => 'admin1',
'password' => '111111',
],
[
'username' => 'admin2',
'password' => '222222',
],
];
//获取post的数据
$date = json_decode( $_POST[ 'date' ] );
$username = $date->username;
$password = $date->password;
// 检测用户是否存在
foreach ( $db as $value ){
if ( $value[ 'username' ] === $username ){
if ( $value[ 'password' ] === $password ){
echo json_encode( [ 'status' => 1, 'msg' => '登录成功,正在跳转…' ] );
exit;
}
}
}
echo json_encode( [ 'status' => 0, 'msg' => '用户名或密码错误,请重试' ] );<?php echo '<h3 align="center"> 后台管理中心</h3 >';
批改老师:天蓬老师批改时间:2019-02-14 09:11:23
老师总结:写得还算完整, 前后台交互的逻辑是正确的