使用 JavaScript 发出 HTTP 请求有多种方法,其中最常用的是使用内置的'XMLHttpRequest'对象或使用现代的'fetch API'。下面是使用这两种方法之一来发出 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 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);
  });

以上代码示例分别使用了'XMLHttpRequest'和'fetch API'来发出 GET 请求,并在请求成功后将响应数据打印到控制台。你可以根据需要自行调整代码以适应其他类型的请求(例如 POST 请求)或添加其他功能(例如错误处理、请求头等)。

请注意,这只是一种常见的使用方式,你可以根据你的具体需求和项目框架来选择适合你的方法。

JavaScript 发出 HTTP 请求:XMLHttpRequest 和 Fetch API

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

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