01_AJAX简介.html 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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>这是一个网页</title>
  8. </head>
  9. <body>
  10. <h1>这是客户端</h1>
  11. <!--
  12. 把服务器中的数据在网页中显示出来
  13. -->
  14. <button id="btn">点击加载数据</button>
  15. <script>
  16. //点击按钮以后,自动去加载服务器的数据
  17. const btn = document.getElementById("btn")
  18. btn.onclick = () => {
  19. //向服务器发送请求
  20. /*
  21. 在js中向服务器发送的请求加载数据的技术叫AJAX
  22. AJAX
  23. -A :异步 J:JavaScript A:and(和) X:xml
  24. -异步的js和xml
  25. -它的作用就是通过js向服务器发送请求来加载数据
  26. -xml是早期AJAX使用的数据格式(占的空间大,传输速度慢,不好解析)
  27. 比如:
  28. <student>
  29. <name>孙悟空</name>
  30. </student>
  31. -目前数据格式都使用json(占的空间小,传输速度更快)
  32. {
  33. "name":"孙悟空"
  34. }
  35. -可以选择的方案
  36. (1)、XMLHTTPRequest(xhr)
  37. (2)、Fetch
  38. 以上两种都是浏览器原生就支持的
  39. (3)、Axios(第三方的)
  40. -CORS:跨域资源共享
  41. -跨域请求
  42. -如果两个网站的完整域名不相同
  43. a网站:http://haha.com
  44. b网站:http://heihei.com
  45. -跨域需要检查三个东西:
  46. 协议 域名 端口号
  47. 三个只要有一个不同,就算跨域
  48. -当我们通过AJAX去发送跨域请求时,
  49. 浏览器为了服务器的安全,会阻止JS读取到服务器的数据
  50. -解决方案
  51. -在服务器中设置一个允许跨越的头
  52. Access-Control-Allow-Origin
  53. -允许哪些客户端访问我们的服务器
  54. */
  55. //xhr
  56. //创建一个新的xhr对象,xhr表示请求信息
  57. const xhr = new XMLHttpRequest()
  58. //设置请求的信息
  59. xhr.open("GET","http://localhost:3000/students")
  60. //发送请求
  61. xhr.send()
  62. }
  63. </script>
  64. </body>
  65. </html>