其他分享
首页 > 其他分享> > 原生 ajax 详细讲解

原生 ajax 详细讲解

作者:互联网

本章主要内容是:每一块的详解,XMLHttpRequest 类型对象、open() 方法开启请求、setRequestHeader() 方法设置请求头、send() 方法发送请求、相应状态分析(readyState 属性、事件处理函数)

1、XMLHttpRequest 类型对象


    // 1、创建一个 XMLHTTPRequest 类型对象
    var xhr = null;
    // 兼容写法
    if (window.XMLHttpRequest){
        // 标准浏览器
        xhr = new XMLHttpRequest();
    } else {
        // IE6浏览器
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }


2、open() 方法开启请求

// 2、open() 方法开启请求
xhr.open("GET", "https://jsonplaceholder.typicode.com/users");

3、setRequestHeader() 方法设置请求头


4、send() 方法发送请求

// 3、send() 方法发送一次请求
// 如果是 get 方法请求,不需要在 send 中传参数
// 如果想传参数,直接写在网址上 xhr.open("GET", "https://jsonplaceholder.typicode.com/users?id=1");
// 一般 get 方法求情,不需要设置,而 post 方法必须设置
// xhr.open("POST", "https://jsonplaceholder.typicode.com/users");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("name=wth&age=25");


5、相应状态分析

readyState 属性

readyState状态描述说明
0UNSENT代理 XHR 被创建,但尚未调用 open() 方法
1OPENEDopen() 方法已经被调用,建立了连接
2HEADERS_RECEIVEDsend() 方法已经被调用,并且已经可以获取状态行和响应头
3LOADING响应体下载中, responseText 属性可能已经包含部分数据
4DONE响应体下载完成,可以直接使用 responseText

 


    // 1、创建一个 XMLHTTPRequest 类型对象
    var xhr = null;
    // 兼容写法
    if (window.XMLHttpRequest){
        // 标准浏览器
        xhr = new XMLHttpRequest();
    } else {
        // IE6浏览器
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    console.log("UNSENT",xhr.readyState);
    // 2、open() 方法开启请求
    xhr.open("GET", "https://jsonplaceholder.typicode.com/users");
    console.log("OPENED",xhr.readyState);
    // 3、send() 方法发送一次请求
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("name=wth&age=25");
    // 4、指定回调函数,处理得到的数据
    xhr.onreadystatechange = function (){
        // 通过判断 xhr 的 readyState,确定此次请求是否完成
        if (this.readyState === 2){
            console.log("HEADERS_RECEIVED",xhr.readyState);
        } else if (this.readyState === 3){
            console.log("LOADING",xhr.readyState);
        } else if (this.readyState === 4){
            console.log("DONE",xhr.readyState);
        }
    };

 

 

事件处理函数

xhr.onreadystatechange = function() {
if (this.readyState === 4) {
// 后续逻辑......
}
};

标签:原生,readyState,XMLHttpRequest,请求,方法,xhr,ajax,讲解,open
来源: https://blog.csdn.net/lnmgmgggggdd/article/details/120616701