使用 JavaScript 发出 HTTP 请求有多种方法,其中最常见的方式是使用内置的 XMLHttpRequest 对象或使用现代的 Fetch API。以下是两种方法的示例代码:

使用 XMLHttpRequest 对象发出 GET 请求:

function makeGetRequest(url) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      var response = xhr.responseText;
      console.log(response);
    }
  };
  
  xhr.send();
}

makeGetRequest('https://api.example.com/data');

使用 fetch API 发出 GET 请求:

function makeGetRequest(url) {
  fetch(url)
    .then(function(response) {
      if (response.ok) {
        return response.text();
      } else {
        throw new Error('Network response was not ok.');
      }
    })
    .then(function(data) {
      console.log(data);
    })
    .catch(function(error) {
      console.log('Error:', error.message);
    });
}

makeGetRequest('https://api.example.com/data');

上述代码可以发送 GET 请求并在控制台中打印响应数据。根据需要,你可以根据请求类型和需要发送的数据来调整代码。

JavaScript 发出 HTTP 请求:XMLHttpRequest 和 Fetch API 实例

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

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