ajax异步请求的五个步骤、五种状态(readyState )

226 阅读1分钟
  1. 创建一个XMLHttpRequest异步对象
var xmlhttp;
if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
    if (xmlhttp.overrideMimeType) {
        xmlhttp.overrideMimeType("text/xml");
    }
} else if (window.ActiveXObject) {
    var xmlList = ["MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
    for (let i = 0; i < xmlList.length; i++) {
        try {
            xmlhttp = new ActiveXObject(xmlList[i]);
        } catch (e) {
            console.log("error" + e);
        }
    }
}
if (!xmlhttp) {
    console.log("创建xmlhttprequest对象失败");
}
  1. 设置请求方式和请求地址
xmlhttp.open("GET", "?name=rel&class=1", true);
//注意, 如果是用post方式请求还需要如下配置:
xmlhttp.open("POST", "?name=rel&class=1", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  1. 用send发送请求
xmlhttp.send();
//如果是post方式请求
xmlhttp.send("name=rel&class=1");
  1. 创建回调函数, 监听状态变化
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState === 4) {
        if (xmlhttp.status == 200) {
            console.log("接收返回的数据" + xmlHttp.responseText);
        } else {
            console.log("没有接收到返回数据");
        }
    }
}
//ajax的五种状态(readyState )
 //0 - (未初始化)还没有调用send()方法
 //1 - (载入)已调用send()方法,正在发送请求
 //2 - (载入完成)send()方法执行完成,已经接收到全部响应内容
 //3 - (交互)正在解析响应内容
 //4 - (完成)响应内容解析完成,可以在客户端调用了

1.png

2.png

3.png

4.png

  1. 接收返回的数据
响应的 HTTP 状态码
200: 响应成功
301: 永久重定向 / 永久转移
302: 临时重定向 / 临时转移
304: 本次获取内容是读取缓存中的数据
400: 请求参数错误
401: 无权限访问
404: 访问的资源不存在