异步请求 - 用户数据 - session实战

编辑: admin 分类: 电脑知识 发布时间: 2023-06-14 来源:互联网
login文档中doLogin函数
  1. async function doLogin(obj){
  2. const email = obj.form.email.value;
  3. const password = obj.form.password.value;
  4. if (email.length > 0 && password.length > 0){
  5. const response = await fetch('./lib/user/handle.php', {
  6. method:'POST',
  7. headers: {
  8. 'Content-type':'application/json;charset=utf-8'
  9. },
  10. body:JSON.stringify({
  11. email,
  12. password}),
  13. });
  14. const result = await response.json();
  15. if(result){
  16. alert('登录成功!');
  17. location.href = 'index.php';
  18. }else{
  19. alert('验证失败!');
  20. location.href = 'login.php';
  21. }
  22. }
  23. }
handle文档
  1. session_start();
  2. $users = require __DIR__. '/../../data/user.php';
  3. $json = file_get_contents('php://input');
  4. $newUser = json_decode($json, true);
  5. $salt = 'dmegc';
  6. $email = $newUser['email'];
  7. $password = md5($salt . $newUser['password']);
  8. $newArr2 = array_values(array_filter([1,2,3,4,5,6], function($item){
  9. return $item%2==0;
  10. }));
  11. $result = array_values(array_filter($users, function($user) use ($email, $password){
  12. return $user['password'] === $password && $user['email'] === $email;
  13. }));
  14. $flag = false;
  15. if(count($result)===1){
  16. $flag = true;
  17. $_SESSION['name'] = $result[0]['name'];
  18. }
  19. echo json_encode($flag);
header登录按钮
  1. <a href="login.php"><?php echo isset($_SESSION['name'])?$_SESSION['name'].'注销':'登录/注册'?></a>
总结:

挺简单的内容,可以讲的快一点;留出时间多实战。

【文章原创作者:国外高防服务器 http://www.558idc.com/shsgf.html转载请说明出处】