03_Fetch.html 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <!DOCTYPE html>
  2. <html lang="en">
  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. <style>
  9. table{
  10. border-collapse: collapse;
  11. width: 50%;
  12. }
  13. td,th{
  14. font-size: 20px;
  15. text-align: center;
  16. border: 1px solid #000;
  17. }
  18. caption{
  19. font-size: 30px;
  20. font-weight: bold;
  21. }
  22. </style>
  23. </head>
  24. <body>
  25. <h1>AJAX测试</h1>
  26. <hr>
  27. <button id="btn">点击加载数据</button>
  28. <hr>
  29. <div id="root"></div>
  30. <script>
  31. const btn = document.getElementById("btn")
  32. const root = document.getElementById("root")
  33. btn.onclick = () =>{
  34. /*
  35. fetch:
  36. -fetch是xhr的升级版,采用的是Promise API
  37. -作用和AJAX是一样的,但是使用起来更加友好
  38. -fetch是原生js就支持的一种ajax请求的方式
  39. */
  40. fetch("http://localhost:3000/students")
  41. //不管响应状态码是多少,只要服务器响应回来以后,then就会执行
  42. .then((res)=>{
  43. if(res.status === 200){
  44. //res.json() 可以用来读取json格式的数据,返回的是一个promise
  45. //console.log(res.json());
  46. //在then里面只要出现了promise,直接使用return返回
  47. return res.json()
  48. }else{
  49. throw new Error("加载失败!")
  50. //then里面无论出现什么异常,都可以抛错,最后在catch里面统一处理
  51. }
  52. })
  53. //上一步的返回值会返回到下一步,所以此处的then相当于是读取promise的数据
  54. .then(res=>{
  55. //console.log(res);
  56. //获取到数据后,将数据渲染到页面中
  57. if(res.status == "ok"){
  58. //创建一个table
  59. const table = document.createElement("table")
  60. root.appendChild(table)
  61. table.insertAdjacentHTML("beforeend","<caption>学生列表</caption>")
  62. table.insertAdjacentHTML("beforeend",`
  63. <thead>
  64. <tr>
  65. <th>学号</th>
  66. <th>姓名</th>
  67. <th>年龄</th>
  68. <th>性别</th>
  69. <th>地址</th>
  70. </tr>
  71. </thead>
  72. `)
  73. const tbody = document.createElement("tbody")
  74. table.appendChild(tbody)
  75. //遍历数据
  76. for(let stu of res.data){
  77. tbody.insertAdjacentHTML("beforeend",`
  78. <tr>
  79. <td>${stu.id}</td>
  80. <td>${stu.name}</td>
  81. <td>${stu.age}</td>
  82. <td>${stu.gender}</td>
  83. <td>${stu.address}</td>
  84. </tr>
  85. `)
  86. }
  87. }
  88. })
  89. .catch((err)=>{
  90. console.log("出错了!",err);
  91. })
  92. }
  93. </script>
  94. </body>
  95. </html>