onreadystatechange事件

688 阅读1分钟

onreadystatechange事件

    (1)  面试点 : ajax请求状态
         提问1 : 能简单的说一下ajax有哪几种请求状态吗?
         提问2  ajax发送请求的时候,状态如何变化的 
    (2)  学习目标:  XMLHttpRequest对象两个事件
        xhr.onload : 服务器响应数据执行 ( 一次请求,只会执行一次 )
             当xhr.readyState == 4 才会执行
        xhr.onreadystatechange : ajax请求状态变化执行 (一次请求,会执行多次)
          请求状态: xhr.readyState
          0: 请求未初始化  (open之前,没有设置地址和方法)
          1: 服务器连接已建立 (open之后,已经设置了地址和方法)
          2: 请求已接收 (onreadystatechange事件里面执行,服务器已接收请求)
          3: 请求处理中 (onreadystatechange事件里面执行,服务器正在处理)
          4: 请求已完成,且响应已就绪 (onreadystatechange事件里面执行,服务器正在响应)

     

image.png

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <script>
        //(1).实例化ajax对象
        let xhr = new XMLHttpRequest()
        console.log( xhr.readyState )//0  xhr没有初始化
        
        //(2).设置请求方法和地址
        //get请求的数据直接添加在url的后面 格式是 url?key=value
        xhr.open('get', 'http://ajax-base-api-t.itheima.net/api/getbooks')
        console.log( xhr.readyState )//1  xhr已建立连接 

        //(3).发送请求
        xhr.send()
        console.log( xhr.readyState )//1  xhr已建立连接

        //(4).注册回调函数
        xhr.onreadystatechange = function() {
          console.log( xhr.readyState )//2 3 4  接收请求  处理请求  响应请求
          console.log(xhr.responseText)
        }
    </script>
  </body>
</html>