异步请求fetch API 以及响应数据的处理, 用户数据的接收,session实战
1. 表单的异步请求
async function doLogin(obj){ //async 定义为异步函数
const email = obj.form.email.value
const password =obj.form.password.value
// console.log(email, password);
if(email.length >0 && password.length > 0){
// 异步提交fetch api
// console.log('111');
const res = await fetch('./lib/user/handle.php',{
//请求方法
method:'post',
//设置请求头
headers:{
'content-type':'application/json;charset=utf-8'
},
//将需要传送到服务器上的数据,解析为json
body:JSON.stringify({
email,
password
})
})
// 解析返回的数据 response返回json格式时,用r.json()打印响应的内容
const result = await res.json()
console.log(result);
2.响应数据处理
if(result){
alert('登陆成功')
location.href='index.php'
}else{
alert('验证失败')
location.href='login.php'
}
3.用户数据接收
$json = file_get_contents('php://input');
$user = json_decode($json, true);
$email = $user['email'];
$password = $user['password'];
4.用户过滤
$result = array_values(array_filter($users,function($user)use($email,$password){
return $user['email']===$email&&$user['password']===$password;
}));
$flag = false;
if(count($result)===1){
$flag = true;
$_SESSION['username'] = $result[0]['name'] ;
}
echo json_encode($flag);
5.会话跟踪
session_start();
$username = $_SESSION['username'];
<?php if (isset($username)) :;?>
<?=$username?> <a href='#'>[注销]</a>
<?php else:?>
<a href="login.php">登录</a>
<?php endif?>