在 JavaScript 中,您可以使用 'XMLHttpRequest' 或 'fetch' API 发出 HTTP 请求。以下是使用这两种方法之一的示例:

使用 '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':

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

这些示例中,我们假设您正在向 'https://api.example.com/data' 发送 GET 请求,并希望获取 JSON 格式的响应数据。您可以根据自己的需求,调整请求的 URL、请求方法和处理响应的逻辑。

JavaScript发送HTTP请求: XMLHttpRequest和Fetch API教程

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

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