在 JavaScript 中,你可以使用内置的 XMLHttpRequest 对象或者使用现代浏览器中的 fetch 函数来发出 HTTP 请求。这里提供两种常见的方法:

使用 XMLHttpRequest 对象:

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

使用 fetch 函数:

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

这两种方法可以发送 GET 请求,如果需要发送其他类型的请求(如 POST),可以使用相应的方法和设置请求头。

JavaScript HTTP 请求:XMLHttpRequest 和 Fetch 方法

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

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