普通 open、send、onload

req=new XMLHttpRequest();
//请求方式get、poset,请求目标URL,是否以异步方式执行请求
req.open("GET",'/json/cats.json',true);
//发送请求
req.send();
//处理响应的数据
req.onload=function(){
  json=JSON.parse(req.responseText);
  document.getElementsByClassName('message')[0].innerHTML=JSON.stringify(json);
};

默认 GET 请求的 语法糖 fetch(url).then().then()

return a Promise

fetch US: [fetʃ] 取来 拿来

fetch('/json/cats.json')
    .then(response => response.json())//返回结果转换为JSON 对象
    .then(data => {//处理JSON 对象(JSON 对象转为字符串,并写入元素中)
        document.getElementById('message').innerHTML = JSON.stringify(data);
    })

//then 接收的是函数哦
//response.json() -> jsonObject
//JSON.stringify(jsonObject) -> jsonString

post 请求

const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
//设置 http header
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
//请求的状态变化时,回调函数
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 201){
    const serverResponse = JSON.parse(xhr.response);
    document.getElementsByClassName('message')[0].textContent = serverResponse.userName + serverResponse.suffix;
  }
};
//准备数据
const body = JSON.stringify({ userName: userName, suffix: ' loves cats!' });
//发送请求以及请求所需的数据
xhr.send(body);