要使用 JavaScript 发起 HTTP 请求,你可以使用内置的 XMLHttpRequest 对象或者 fetch 函数。以下是使用这两种方法之一的示例:

使用 XMLHttpRequest 对象:

// 创建一个新的 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();

// 配置 HTTP 请求方法、URL 和异步标志
xhr.open('GET', 'https://api.example.com/data', true);

// 设置请求头(如果需要)
xhr.setRequestHeader('Content-Type', 'application/json');

// 处理请求完成后的回调函数
xhr.onload = function() {
  if (xhr.status === 200) {
    // 请求成功,处理返回的数据
    var response = JSON.parse(xhr.responseText);
    console.log(response);
  } else {
    // 请求失败,处理错误信息
    console.error('请求失败:' + xhr.status);
  }
};

// 发送 HTTP 请求
xhr.send();

使用 fetch 函数:

// 发起 GET 请求
fetch('https://api.example.com/data')
  .then(function(response) {
    if (response.ok) {
      // 请求成功,处理返回的数据
      return response.json();
    } else {
      // 请求失败,抛出一个错误
      throw new Error('请求失败:' + response.status);
    }
  })
  .then(function(data) {
    // 处理返回的数据
    console.log(data);
  })
  .catch(function(error) {
    // 处理错误
    console.error(error);
  });

这些示例展示了如何通过 GET 方法发出 HTTP 请求。如果你需要使用其他 HTTP 方法(如 POST、PUT 等),你可以在 xhr.openfetch 函数的第一个参数中指定。

JavaScript 发起 HTTP 请求:XMLHttpRequest 和 Fetch 方法

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

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