【ajax五种请求状态】

330 阅读1分钟

ajax中我们常用xhr.onload事件,但是面试有可能问到另一种事件,xhr.onreadystatechange\color{red}{xhr.onreadystatechange}事件。

其会在ajax请求状态变化时执行(一次请求执行多次)。

每当readyState改变时,就会调用onreadystatechange这个函数。而readyState中存有XMLHttpRequest五种状态,从0到4变化,可以用代码清楚的展现这个过程,往下看。

基础

先随便放一个ajax请求代码,并替换xhr.onload事件,换上xhr.onreadystatechange\color{red}{xhr.onreadystatechange}事件

<script>
    
        // (1)创建xhr对象,负责发送ajax请求
        let xhr = new XMLHttpRequest()
    
        // (2)设置请求方法和地址
        xhr.open('get',"https://autumnfish.cn/api/joke")
    
        // (3)发送请求
        xhr.send()

        // (4)注册响应事件
        xhr.onreadystatechange = function(){
            console.log(xhr.responseText)
        }
        </script>

此时浏览器会打印三条信息出来,第一条为空

image.png

增进

<script>
        let xhr = new XMLHttpRequest()
        console.log(xhr.readyState) 

        xhr.open('get',"https://autumnfish.cn/api/joke")
        console.log(xhr.readyState)

        xhr.send()
        console.log(xhr.readyState)

        xhr.onreadystatechange = function(){
            console.log(xhr.responseText)
        }
</script>

我们在创建对象、设置方法和地址、发送请求后都打印一下xhr.readyState,查看XMLHttpRequest的五种状态

image.png

解释

此时多了0 1 1三个数字,表明目前其状态有0和1两种

状态0

代表请求未初始化,也就是只有let xhr = new XMLHttpRequest()时,open之前,没有设置方法和地址,没有初始化,此时XMLHttpRequest状态默认为0

image.png

状态1

代表服务器链接已建立,open之后,已经设置了地址和方法

image.png

状态2&3&4

            xhr.onreadystatechange = function(){
            console.log(xhr.responseText)
            console.log(xhr.readyState)
        }

此时我们在onreadystatechange事件里执行打印xhr.readyState,会发现又打印了三个数字。

image.png

其中2代表请求已接收,3代表请求处理中,4代表请求已完成

总结

xhr.onload只有在xhr.readyState == 4时候才会执行

而ajax的请求状态有五种,分别是0未连接,1已连接,234请求处理响应,存储在readyState\color{red}{readyState}中。

完!

期待您的宝贵评论,(ˇωˇ」∠))寄罢...