02_AJAX的使用.html 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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>Document</title>
  8. </head>
  9. <body>
  10. <h1>AJAX测试</h1>
  11. <hr>
  12. <button id="btn">点击加载数据</button>
  13. <div id="root"></div>
  14. <script>
  15. const btn = document.getElementById("btn")
  16. const root = document.getElementById("root")
  17. btn.onclick = () =>{
  18. //创建一个xhr对象
  19. const xhr = new XMLHttpRequest()
  20. //设置响应体的类型,设置后会自动对数据进行类型转换
  21. xhr.responseType = "json"
  22. //可以为xhr对象绑定一个load事件
  23. //表示xhr中的数据加载完成以后,function()才会执行
  24. xhr.onload = function(){
  25. //xhr.status 表示响应状态码
  26. //console.log(xhr.status);
  27. if(xhr.status === 200){
  28. //xhr.response 表示响应信息
  29. //方式一:收到转换
  30. // const result = JSON.parse(xhr.response)
  31. // console.log(result.status,result.data)
  32. //方式二:创建完xhr对象后,设置xhr.responseType = "json"
  33. //读取响应信息
  34. //console.log(xhr.response);
  35. const result = xhr.response
  36. //判断数据是否正确
  37. if(result.status == "ok"){
  38. //创建一个ul
  39. const ul = document.createElement("ul")
  40. //将ul插入到root中
  41. root.appendChild(ul)
  42. //遍历数据
  43. for(let stu of result.data){
  44. ul.insertAdjacentHTML("beforeend",`<li>${stu.id} - ${stu.name} - ${stu.age} - ${stu.gender} - ${stu.address}</li>`)
  45. }
  46. }
  47. }
  48. }
  49. //设置请求信息
  50. xhr.open("get","http://localhost:3000/students")
  51. //发送请求
  52. xhr.send()
  53. }
  54. </script>
  55. </body>
  56. </html>