博客列表 >fetch的异步和同步以及Mock.js使用

fetch的异步和同步以及Mock.js使用

时间在渗透
时间在渗透原创
2022年11月16日 02:36:43734浏览

作业代码

  1. <!DOCTYPE html>
  2. <html lang="zh">
  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的异步和同步以及Mock.js使用</title>
  8. <style type="text/css">
  9. *{box-sizing:border-box;margin:0;padding:0;}
  10. body{background-color:#f2f2f2;font-size:16px;}
  11. h1,h2,h3,h4{margin-bottom:15px;}
  12. input[type=checkbox]+label,input[type=radio]+label{margin-right:10px;margin-left:5px;height:36px;line-height:36px;}
  13. button{padding:0 18px;height:36px;border:1px solid transparent;border-radius:2px;background-color:#03a9f4;color:#fff;text-align:center;white-space:nowrap;font-size:14px;line-height:36px;cursor:pointer;}
  14. button:hover{opacity:.8;}
  15. pre{display:block;overflow:auto;margin:15px 0;padding:15px;border-radius:6px;background-color:#f5f5f5;color:#333;word-wrap:break-word;font-size:13px;line-height:1.4;word-break:break-all;}
  16. #app{margin:30px auto;padding:20px;max-width:970px;background-color:#fff;}
  17. .mock{position:relative;}
  18. .mock>.refresh{position:absolute;right:0;bottom:0;border:none;border-radius:0 0 6px 0;background-color:#03a9f4;color:#fff;cursor:pointer;}
  19. </style>
  20. </head>
  21. <body>
  22. <div id="app">
  23. <div class="mock">
  24. <h2>Mock.js 演示</h2>
  25. <pre></pre>
  26. <button class="refresh" onclick="mockTest(this)">刷新</button>
  27. </div>
  28. <div class="fetch">
  29. <h2>fetch API演示</h2>
  30. <div class="btn-group">
  31. <button onclick="fetchTest(this, 'GET')">发送GET请求</button>
  32. <button onclick="fetchTest(this, 'POST')">异步发送POST请求</button>
  33. <button onclick="fetch2Test(this, 'PUT')">同步发送PUT请求</button>
  34. <button onclick="fetch2Test(this, 'PATCH')">同步发送PATCH请求</button>
  35. <button onclick="fetch2Test(this, 'DELETE')">同步发送DELETE请求</button>
  36. </div>
  37. <pre></pre>
  38. </div>
  39. </div>
  40. <script src="https://cdn.staticfile.org/Mock.js/1.0.0/mock-min.js" type="text/javascript" charset="utf-8">
  41. </script>
  42. <script type="text/javascript" charset="utf-8">
  43. document.querySelector('.mock>.refresh').click();
  44. // mock测试
  45. function mockTest(ele) {
  46. let mock = {
  47. "id": Mock.mock('@integer(100000, 999999)'),
  48. "name": Mock.mock('@cname'),
  49. "ip": Mock.mock('@ip'),
  50. "region": Mock.mock('@region'),
  51. "province": Mock.mock('@province'),
  52. "city": Mock.mock('@city')
  53. }
  54. ele.parentNode.querySelector('pre').innerHTML = JSON.stringify(mock, null, 2)
  55. }
  56. // 异步方式
  57. function fetchTest(ele, method = 'GET') {
  58. let obj = getMockData(method);
  59. fetch(obj.url, obj.option).then(response => response.json()).then(json => {
  60. ele.parentNode.parentNode.querySelector('pre').innerHTML = JSON.stringify(json, null, 2)
  61. });
  62. }
  63. // 同步方式
  64. async function fetch2Test(ele, method = 'GET') {
  65. let obj = getMockData(method);
  66. // 1. 等待结果再进行下一步操作,返回响应对象
  67. const response = await fetch(obj.url, obj.option);
  68. // 2. 将响应结果,转为json, json()
  69. const result = await response.json();
  70. ele.parentNode.parentNode.querySelector('pre').innerHTML = JSON.stringify(result, null, 2)
  71. }
  72. // 获取测试数据
  73. function getMockData(method){
  74. let url = '';
  75. let option = {};
  76. option.method = method;
  77. option.headers = {
  78. 'Content-type': 'application/json; charset=UTF-8',
  79. }
  80. // GET方法没有 body参数, 其他请求必须要有body
  81. switch (method) {
  82. case 'GET':
  83. url = 'https://jsonplaceholder.typicode.com/todos/' + Mock.mock('@integer(1, 200)');
  84. break;
  85. case 'POST':
  86. url = 'https://jsonplaceholder.typicode.com/posts/';
  87. option.body = JSON.stringify({
  88. userId: Mock.mock('@integer(100000, 999999)'),
  89. title: Mock.mock('@ctitle'),
  90. body: Mock.mock('@cparagraph'),
  91. })
  92. break;
  93. case 'PUT':
  94. url = 'https://jsonplaceholder.typicode.com/posts/' + Mock.mock('@integer(1, 100)');
  95. option.body = JSON.stringify({
  96. userId: Mock.mock('@integer(100000, 999999)'),
  97. title: Mock.mock('@ctitle'),
  98. body: Mock.mock('@cparagraph'),
  99. })
  100. break;
  101. case 'PATCH':
  102. url = 'https://jsonplaceholder.typicode.com/posts/' + Mock.mock('@integer(1, 100)');
  103. option.body = JSON.stringify({
  104. title: Mock.mock('@ctitle'),
  105. })
  106. break;
  107. case 'DELETE':
  108. url = 'https://jsonplaceholder.typicode.com/posts/' + Mock.mock('@integer(1, 100)');
  109. break;
  110. }
  111. return {url: url, option: option}
  112. }
  113. </script>
  114. </body>
  115. </html>

演示效果

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