Blogger Information
Blog 94
fans 0
comment 0
visits 92652
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
【PHP】重点:前后端数据交互:fetch:api *****五星重点
可乐随笔
Original
2071 people have browsed it

前后端数据交互:fetch:api

1.前端代码

  1. <!-- 用户登录 -->
  2. <form class="login" id="login">
  3. <table>
  4. <caption>
  5. 用户登录
  6. </caption>
  7. <tbody>
  8. <tr>
  9. <td><label for="email">邮箱:</label></td>
  10. <td><input type="email" name="email" id="email" /></td>
  11. </tr>
  12. <tr>
  13. <td><label for="password">密码:</label></td>
  14. <td><input type="password" name="password" id="password" /></td>
  15. </tr>
  16. <tr>
  17. <td colspan="2"><button type="button" onclick=check(this)>提交</button></td>
  18. </tr>
  19. </tbody>
  20. </table>
  21. </form>
  22. <p>
  23. <a href="register.html">没有帐号,请先注册</a>
  24. </p>
  25. </main>
  26. <script>
  27. async function check(btn) {
  28. //email
  29. const email = btn.form.email.value.trim();
  30. //password
  31. const password = btn.form.password.value.trim();
  32. //非空验证
  33. if (email.length > 0 && password.length > 0) {
  34. //异步提交:fetch api
  35. const response = await fetch('./lib/user/login.php', {
  36. //请求类型:post
  37. method: 'POST',
  38. //请求头
  39. headers: {
  40. 'Content-Type': 'application/json;charset=utf-8',
  41. },
  42. //数据
  43. body: JSON.stringify({
  44. email,
  45. password
  46. })
  47. });
  48. //2.解析数据
  49. const data = await response.json();
  50. console.log(data);
  51. } else {
  52. alert('邮箱或密码不能为空');
  53. return false;
  54. }
  55. }
  56. </script>

2. 后端代码

  1. <?php
  2. //获取登录数据
  3. // print_r($_POST);
  4. //不行,因为不是通过传统的表单格式提交,用的是JSON
  5. //json当成文本原始数据流来接收
  6. $json = file_get_contents('php://input');
  7. // $json 并非PHP能识别的数据类型,它只是json格式的字符串
  8. // $json -> php.array, true:数组
  9. $user = json_decode($json,true);
  10. //验证
  11. //这里暂不处理
  12. //返回:php.string -> json 返回,前端只认识json
  13. // echo json_encode('验证成功');
  14. echo json_encode($user);
  15. `
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