1. 什么是Ajax


Asynchronous JavaScript and XML
(异步的JavaScript 和XML)

  • Ajax不是某种编程语言
    是一种在无需重新加载整个网页的情况下,能够局部更新网页的技术

2.同步异步


同步:客户端在等待服务器端响应的过程中,不能做任何事情

异步:客户端发起请求,在服务器端响应的过程中,可以进行其他的操作

  1. <script>
  2. /*
  3. 同步 就是客户端向服务器发送请求的过程中,用户不可以进行其他操作
  4. 异步 就是客户端向服务器发送请求的过程中,用户可以进行其他操作
  5. */
  6. console.log("1")
  7. setTimeout(function(){
  8. console.log("http")
  9. },1000)
  10. console.log("2")
  11. </script>

3.json数据


01.png

  • 7a431860cea3b5ebcbc4f23bd4ff10e5_704x375.png

4.一个完整的ajax的步骤


1.创建ajax核心对象

2.与服务器建立连接

3.发送请求

  1. 请求的地址 url
  2. 请求的方式 type:”get”
  3. 请求的数据类型 dataType: “json”

    4.响应

5.ajax实例

  1. <body>
  2. <p id="name"></p>
  3. <p id="age"></p>
  4. <script>
  5. /* JSON.parse() json格式的字符串转换为Json对象 */
  6. var url = "https://www.easy-mock.com/mock/5d67436424fd60626abfe912/ajax/base";
  7. //easy-mock的接口url
  8. var xhr = new XMLHttpRequest();
  9. xhr.open('get',url,true)
  10. xhr.send()
  11. xhr.onreadystatechange = function(){
  12. // console.log(xhr.readyState)
  13. // console.log(xhr.status)
  14. if(xhr.readyState == 4 && xhr.status == 200){
  15. var res = JSON.parse(xhr.responseText);
  16. console.log(res.data.name)
  17. var name = document.getElementById("name")
  18. name.innerHTML = res.data.name;
  19. }
  20. }
  21. </script>
  22. </body>