Ajax学习记录

56 阅读3分钟

ajax

学习XMLHttpRequest时的笔记

const xhr = new XMLHttpRequest();
// xhr被创建,此时xhr.readystate为xhr.UNSENT(0),还未调用open方法
// 之后调用xhr.open初始化一个请求,xhr.open(method,url,async,user,password),open可以接收5个参数,前两个必传
// method(请求方法,必传),url(请求地址,必传),async(是否异步,默认为true),user(用户名),password(密码),用户名和密码用于认证用途
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');
// open方法被调用后,此时xhr.readystate的值就变为xhr.OPENED(1),表示open方法已调用,readystate为xhr.OPENED这个状态时
// 才可以调用setRequestHeader()来设置请求头
xhr.setRequestHeader('Content-Type','application/json;charset=utf-8');
// setRequestHeader用于设置请求头,采用键值对的方式
// 一般get请求不用设置content-type,post请求才需要设置content-type请求头
xhr.responseType = '';
// responseType为设置响应体的格式,设置为空与设置为'text'相同,可选的格式有:"arraybuffer"、"blob"、"document"、"json"、"text"
// responseType的设置也需要在open方法和send方法之间
xhr.send(null);
// send方法用于正式向后端发起请求,send里传入的内容为请求体里携带的参数,可以有下面这些值
// xhr.send('string');
// xhr.send(new Blob());
// xhr.send(new Int8Array());
// xhr.send(document);
// send方法可传内容参考https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/send
// send方法调用之后xhr.readystate的值变为xhr.HEADERS_RECEIVED(2),表示send方法已调用,且头部和状态已获得
// 之后xhr.readystate的值会变为xhr.LOADING(3),响应数据获取中,responseText已包含部分数据
// 响应数据全部拿到后readystate的值变为xhr.DONE(4)
xhr.addEventListener('readystatechange', function() {
  if(xhr.readyState !== xhr.DONE) {
    return;
  }
  if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
    // xhr.status为响应的状态码,其含义可以参考下面的链接
    // https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status
    console.log(xhr.response);
  } else {
    console.log('未接收到数据');
  }
})
// xhr.readystate的值变化时,会触发readystatechange事件,我们可以在readystate变为xhr.DONE时拿到响应数据
// 根据拿到的响应数据再做操作
// 以上就是ajax操作的主要流程,再看一下xhr的其它属性

/**
 * xhr.statusText
 * 返回状态对应的文本信息,若后端没有指定,则为OK
 * 在readystate为xhr.LOADING与xhr.DONE时才有值,否则为空字符串
 * */

/**
 * xhr.timeout
 * 请求超时时间,代表一个请求在被自动终止前所消耗的毫秒数,默认为0,意味着没有超时
 * 需要在open方法之后,send方法之前设置超时时间
 * */

/**
 * xhr.ontimeout
 * 与xhr.timeout配合使用,在请求超时时触发此事件的回调函数
 * */

  /**
  * xhr.upload
  * xhr.upload属性返回一个XMLHttpRequestUpload对象,可以通过对这个对象绑定事件来获取请求的进度
  * 之后再详细学一下这个是如何获取进度的
  * */

/**
 * xhr.withCredentials
 * 属性是一个布尔值,它指示了是否该使用类似 cookie、Authorization 请求头或者 TLS 客户端证书等凭据进行跨站点访问控制
 * (Acess-Control)请求,还指示是否在响应中忽略cookie,默认值是false,如果需要在自己的域中设置cookie,则需要在请求
 * 前将withCredentials设置为true。注意withCredentials对同源的请求无效
 * */

/**
 * getResponseHeader()
 * 获取响应头的值,传入键的字符串值,类似map.get('xxx'),localstorage.getItem('xxx')等
 * */

  /**
  * getAllResponseHeaders()
  * 返回所有响应头,以换行符作为分隔
  * */