在 JavaScript 中,可以使用内置的'XMLHttpRequest' 对象或'fetch' 函数来发出 HTTP 请求。

使用'XMLHttpRequest' 示例:

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

使用'fetch' 示例:

fetch('https://api.example.com/data')
  .then(function (response) {
    if (response.ok) {
      return response.json();
    } else {
      throw new Error('Error: ' + response.status);
    }
  })
  .then(function (data) {
    console.log(data);
  })
  .catch(function (error) {
    console.log(error);
  });

这些示例中,我们发起了一个 GET 请求到'https://api.example.com/data',并处理返回的数据。你可以根据自己的需求修改 URL、请求方法(GET、POST 等)以及其他请求参数。

JavaScript HTTP 请求:XMLHttpRequest 和 fetch 方法详解

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

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