博客列表 >【PHP】重点:前后端数据交互:fetch:api *****五星重点

【PHP】重点:前后端数据交互:fetch:api *****五星重点

可乐随笔
可乐随笔原创
2022年12月14日 21:05:342063浏览

前后端数据交互: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. `
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议