批改状态:合格
老师批语:
<!-- button 的 type 属性设置为 button,取消默认提交 --><button type="button" onclick="doLogin(this)">提交</button>
函数功能:
async function doLogin(obj) {// 获取用户输入数据const email = obj.form.email.value;const password = obj.form.password.value;// 非空验证if (email.length > 0 && password.length > 0) {// 将用户数据发送给后台脚本(handle.php)同时发起异步请求const response = await fetch('./lib/user/handle.php', {method: 'POST',headers: {'Content-Type': 'application/json;charset = utf-8'},body: JSON.stringify({email, password})})// 解析返回的数据 response返回json格式时,用r.json()打印响应的内容const result = await response.json();if (result) {alert('登录成功');// 首页跳转location.href = 'index.php';} else {alert('验证失败,请核实信息');location.href = 'login.php';}}}
脚本功能:
// 开启 sessionsession_start();// 引入用户模拟数据,用于比对用户输入数据$users = require __DIR__.'/../../data/user.php';// 1.接收表单数据 不能使用传统的超全局变量$_POST来接收// json当成文本流原始数据来接收$json = file_get_contents('php://input');// 2.$json 并非php所能识别的数据类型 需要将json字符串转成php数组$user = json_decode($json, true);// 3.解析用户提交的数据 和数据表里的数据进行匹配$email = $user['email'];$salt = 'wwwphpcn23';$password = md5($user['password'] . $salt);// 4. 用户过滤(比对用户输入数据)$result = array_values(array_filter( $users,function ($user) use ($email, $password) {return $user['email'] === $email && $user['password'] === $password;}));// 5.结果分析,并将结果返回请求页面// 默认检查不通过$flag = false;if (count($result) === 1) {$flag = true;$_SESSION['name'] = $result[0]['name'];}echo json_encode($flag);
头部模板 header.php
// 开启 sessionsession_start();<nav><a href="index.php">首页</a><?php foreach ($navs as $v) : extract($v); ?><a href="<?= $url ?>"><?= $name ?></a><?php endforeach; ?><?php if (isset($_SESSION['name'])): ?><a href="login.php"><?= $_SESSION['name'] ?></a><?php else: ?><a href="login.php">登录</a><?php endif; ?></nav>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号