要使用 JavaScript 发出 HTTP 请求,您可以使用浏览器内置的 XMLHttpRequest 对象或者更现代的 Fetch API。以下是两种方法的示例:

使用 XMLHttpRequest 对象:

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

使用 Fetch API:

fetch('https://api.example.com/data')
  .then(function(response) {
    if (response.ok) {
      return response.json();
    }
    throw new Error('Network response was not ok.');
  })
  .then(function(data) {
    console.log(data);
  })
  .catch(function(error) {
    console.log('Error:', error.message);
  });

这些示例分别展示了通过 GET 方法获取 JSON 数据的简单情况。您可以根据需要自定义请求的类型(GET、POST 等)和处理响应的逻辑。请确保将 URL 替换为您要请求的实际 API 地址,并根据需要进行错误处理和数据处理。

请注意,以上示例适用于在浏览器中运行 JavaScript。如果您想在服务器端(如 Node.js)中发出 HTTP 请求,可以使用 Node.js 的内置 http 模块或者像 Axios、node-fetch 等外部库。

JavaScript HTTP 请求:XMLHttpRequest 和 Fetch API 示例

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

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