Blogger Information
Blog 40
fans 0
comment 0
visits 16011
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
异步请求fetch API 以及响应数据的处理, 用户数据的接收,session实战
飞天001
Original
279 people have browsed it

异步请求fetch API 以及响应数据的处理, 用户数据的接收,session实战

1. 表单的异步请求

  1. async function doLogin(obj){ //async 定义为异步函数
  2. const email = obj.form.email.value
  3. const password =obj.form.password.value
  4. // console.log(email, password);
  5. if(email.length >0 && password.length > 0){
  6. // 异步提交fetch api
  7. // console.log('111');
  8. const res = await fetch('./lib/user/handle.php',{
  9. //请求方法
  10. method:'post',
  11. //设置请求头
  12. headers:{
  13. 'content-type':'application/json;charset=utf-8'
  14. },
  15. //将需要传送到服务器上的数据,解析为json
  16. body:JSON.stringify({
  17. email,
  18. password
  19. })
  20. })
  21. // 解析返回的数据 response返回json格式时,用r.json()打印响应的内容
  22. const result = await res.json()
  23. console.log(result);

2.响应数据处理

  1. if(result){
  2. alert('登陆成功')
  3. location.href='index.php'
  4. }else{
  5. alert('验证失败')
  6. location.href='login.php'
  7. }

3.用户数据接收

  1. $json = file_get_contents('php://input');
  2. $user = json_decode($json, true);
  3. $email = $user['email'];
  4. $password = $user['password'];

4.用户过滤

  1. $result = array_values(array_filter($users,function($user)use($email,$password){
  2. return $user['email']===$email&&$user['password']===$password;
  3. }));
  4. $flag = false;
  5. if(count($result)===1){
  6. $flag = true;
  7. $_SESSION['username'] = $result[0]['name'] ;
  8. }
  9. echo json_encode($flag);

5.会话跟踪

  1. session_start();
  2. $username = $_SESSION['username'];
  3. <?php if (isset($username)) :;?>
  4. <?=$username?> <a href='#'>[注销]</a>
  5. <?php else:?>
  6. <a href="login.php">登录</a>
  7. <?php endif?>
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post