要发送一个请求,需要使用 XMLHttpRequest 对象或 fetch API。

使用 XMLHttpRequest 对象:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data');
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  } else {
    console.log('Request failed.  Returned status of ' + xhr.status);
  }
};
xhr.send();

使用 fetch API:

fetch('https://example.com/api/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
JavaScript 发送 HTTP 请求:XMLHttpRequest 和 Fetch API