你所不知道的原生ajax的readyState

71 阅读1分钟

一、readyState

0: unsend,代理被创建,尚未调用open方法

1: opened,open已调用

2: headers received,send方法已调用,且头部和状态已可活动

3: loading,下载中,respenseText属性保护部分数据

4: done,下载已完成

二、open

五个参数,第一个是method,第一个url,第三个是是否一步,false:send方法知道答复前不会返回

三、代码

const xhr = new XMLHttpRequest();
/*xhr.onreadystatechange = function () {
    console.log('readystate:', xhr.readyState); // 123....、4
}*/
xhr.open('get', 'http://f.sinaimg.cn/default/10f2c867/20230113/big_size.jpg', true);
xhr.send();
xhr.onreadystatechange = function () {
    console.log('readystate:', xhr.readyState); // 23....、4
}

四、readyState变化

const xhr = new XMLHttpRequest();
/* xhr.onreadystatechange = function () {
    console.log('readystate:', xhr.readyState); // 14
}*/
xhr.open('get', 'http://f.sinaimg.cn/default/10f2c867/20230113/big_size.jpg', false);
/*xhr.onreadystatechange = function () {
    console.log('readystate:', xhr.readyState); // 14
}*/
xhr.send();
xhr.onreadystatechange = function () {
    console.log('readystate:', xhr.readyState); // 无返回
}

注意‬onreadystate change监听‬的‬时机‬,以及‬open时‬是‬同步‬还是‬异步‬,均会‬影响‬readystate的‬变化‬