XHR基础使用

解决:客户端和服务器的异步通信 (减少网络延迟或损耗, 提高用户体验, 并增强了JS在浏览器上操作HTTP的能力)

  1. let xhr = new XMLHttpRequest();
  2. xhr.open('GET', url);
  3. xhr.response = 'json';
  4. xhr.onload = () => {
  5. // xhr.response
  6. }
  7. xhr.onerror = () => {
  8. // error
  9. }
  10. xhr.send();

缺陷:

  • request、response和事件监听在一个对象中
  • 需要实例化才能发送请求
  • 不符合职责单一的原则

XHR运作机制

image.png

fetch

参考:

https://mp.weixin.qq.com/s/DuHwr_waLMh_DA9vHLhbWg

https://time.geekbang.org/column/article/135127