博客列表 >【JS】fetch常用案例:参考模板

【JS】fetch常用案例:参考模板

可乐随笔
可乐随笔原创
2022年12月09日 12:34:081479浏览

fetch常用案例:参考模板

HTML示范代码:

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>fetch</title>
  8. </head>
  9. <body>
  10. <div style="display: inline-grid; gap: 1em">
  11. <button onclick="getHtml(this)">GET-HTML</button>
  12. <button onclick="getJSON(this)">GET-JSON</button>
  13. <button onclick="postJSON(this)">POST-JSON</button>
  14. </div>
  15. <script>
  16. // fetch: 发起http请求,返回 Promise对象,该对象会在请求响应被resolve,返回Response
  17. //
  18. // GET:HTML
  19. const getHtml = async function (btn) {
  20. // 响应对象
  21. const response = await fetch('http://site.io/test1.php', {
  22. method: 'GET',
  23. });
  24. // 处理数据
  25. const data = await response.text();
  26. console.log(data);
  27. // 将html字符串,解析/包装成DOM元素对象
  28. let domparser = new DOMParser();
  29. let doc = domparser.parseFromString(data, 'text/html');
  30. // 将data,解析成了一个完整的html文档对象
  31. console.log(doc);
  32. let ele = doc.body.firstElementChild;
  33. console.log(ele);
  34. // 将ul添加到页面中
  35. if (btn.nextElementSibling.tagName !== 'UL') {
  36. btn.after(ele);
  37. } else {
  38. btn.nextElementSibling.remove();
  39. }
  40. };
  41. // GET:JSON
  42. const getJSON = async function (btn) {
  43. // 响应对象
  44. const response = await fetch('http://site.io/test2.php', {
  45. method: 'GET',
  46. });
  47. // 处理数据
  48. const data = await response.json();
  49. console.log(data);
  50. // 用表格将数据渲染到页面中
  51. const table = document.createElement('table');
  52. table.border = 1;
  53. const caption = table.createCaption();
  54. caption.textContent = '购物车';
  55. const thead = table.createTHead();
  56. thead.innerHTML = '<tr><td>ID</td><td>品名</td><td>单价</td></tr>';
  57. const tbody = table.createTBody();
  58. data.forEach((item) => {
  59. const tr = `
  60. <tr>
  61. <td>${item.id}</td>
  62. <td>${item.name}</td>
  63. <td>${item.price}</td>
  64. </tr>
  65. `;
  66. tbody.innerHTML += tr;
  67. });
  68. // 将ul添加到页面中
  69. if (btn.nextElementSibling.tagName !== 'TABLE') {
  70. btn.after(table);
  71. } else {
  72. btn.nextElementSibling.remove();
  73. }
  74. };
  75. // POST: JSON(参考模板)
  76. const postJSON = async function (btn) {
  77. const response = await fetch('api', {
  78. // 请求类型
  79. method: 'POST',
  80. // 跨域
  81. mode: 'cors',
  82. // 请求头
  83. headers: {
  84. // 内容类型
  85. 'Content-Type': 'application/json;charset=utf-8',
  86. },
  87. // 将数据解析为JSON字符串发送
  88. body: JSON.stringify({ id: 4, name: '面包', price: 50 }),
  89. });
  90. //
  91. const data = await response.text();
  92. console.log(data);
  93. };
  94. </script>
  95. </body>
  96. </html>

PHP接口代码示范:

test1.php

  1. <?php
  2. header("access-control-allow-origin: *");
  3. ?>
  4. <ul>
  5. <li><a href="">item1</a></li>
  6. <li><a href="">item2</a></li>
  7. <li><a href="">item3</a></li>
  8. </ul>

test2.php

  1. <?php
  2. // 允许跨域
  3. header("access-control-allow-origin: *");
  4. $data = [
  5. ['id'=>1,'name'=>'西瓜', 'price'=>20],
  6. ['id'=>2,'name'=>'蛋糕', 'price'=>100],
  7. ['id'=>3,'name'=>'大馍', 'price'=>10],
  8. ];
  9. echo json_encode($data);
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议