XMLHttpRequest 对象

XMLHttpRequest

作用

  1. 在不刷新页面的情况下,能够发起请求(ajax的原理

使用

  1. 先初始化构造函数,生成一个实例

    const xhrRequest = new XMLHttpRequest();
    
  2. 初始化请求

    xhrRequest.open('POST','some.php','true'); //POST类型的异步请求  
    
  3. 发送请求数据

    xhrRequest.send("id=1&type=0");
    
  4. 设置监听获取数据

    xhrRequest.onreadystatechange = function () {
        if(xhrRequest.readyState == XMLHttpRequest.DOME && xhrRequest.status == 200) {
         	console.log(xhrRequest.responseText);  
         }
    }
    

语法

  1. 属性

    • readyState : 返回请求的状态码 (只读)

    • response : 返回整个响应实体(只读),返回的类型有:ArrayBuffer、Blob、Document 、DOMString ,可以通过下面的responseType设置响应的类型

    • responseType: 指定响应的数据类型,默认是text,可以设置的类型有:arraybuffer 、 blob、 document、json、 text、ms-stream

    • status: 返回一个数字,代表响应的状态(只读)

    • statusText:返回一个完整的响应状态文本 (只读)

    • responseText : 返回一个DOMString(只读)

    • responseXML : 返回一个Document (只读)

    • timeout : 设置最大的请求时间

    • upload : 返回上传的进度(只读)

    • withCredentials : 设置一个boolean 值,用来表示跨域的是否带有授权信息

      (注:还有个别的非标准属性)

  2. 事件

    • onreadystatechange() : readyState 发生改变时,会调用

    • ontimeout() : 请求超时的时候会调用

    • onloadstart()

    • onload()

    • onloadend()

    • onerror()

    • onprogress() : 进度

    • **addEventListener() **: 监听器

    • onabort()

  3. 方法

    • abort() :中止请求

    • getAllResponseHeaders() : 返回整个请求头

    • getResponseHeader(name) : 返回指定的请求头属性的值,例如:

      const client = new XMLHttpRequest();
      client.open("GET","somefile.txt",true); // 设置异步请求
      client.send(); // 发送请求
      client.onreadystatechange = function() {
          if(this.readyState == this.HEADERS_RECCWIVED) {   //此时请求头已经返回了
              let contentType = client.getResponseHeader("Content-Type"); // 返回响应头中的Content-Type 的值 
             	 console.log(contentType);
             }
      }
      
    • open(method, url, [async], [user], [password]) : 初始化请求

      • async : 是否异步
      • user && password : 用于认证用途
    • overrideMimeType()

    • send([body]) : 发送数据

      • body 可以设置为 Document 、XMLHttpRequestBodyInit 、 null 类型。
    • setRequestHeader() :

      (注:还有一些非标注方法)

原文地址:https://www.cnblogs.com/zxn-114477/p/15254484.html