使用 JavaScript 发出 HTTP 请求可以使用内置的 'XMLHttpRequest' 对象或者使用现代的 'fetch' API。下面是两种方法的示例:

使用 XMLHttpRequest:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    const response = JSON.parse(xhr.responseText);
    console.log(response);
  }
};
xhr.send();

使用 fetch API:

fetch('https://api.example.com/data')
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.log(error));

请注意,以上示例是基本的 GET 请求示例,如果需要发送 POST 请求或添加其他自定义选项,您需要进行额外的配置和参数设置。

JavaScript HTTP 请求:XMLHttpRequest 和 fetch API

原文地址: https://www.cveoy.top/t/topic/Rr2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录