异步请求和同步请求的概念

同步请求会阻塞代码执行,而异步请求允许代码继续执行,不用等待请求完成。

XMLHttpRequest 实现同步和异步请求

同步请求

var xhr = new XMLHttpRequest();
xhr.open('GET', '<https://api.example.com/data>', false); // 第三个参数指定为 false 表示同步请求
xhr.send();

异步请求

var xhr = new XMLHttpRequest();
xhr.open('GET', '<https://api.example.com/data>', true); // 第三个参数指定为 true 表示异步请求
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(xhr.responseText);
  }
};
xhr.send();