使用 JavaScript 发送 HTTP 请求可以使用内置的 'XMLHttpRequest' 对象或者使用现代的 'fetch' API。下面我将为你提供两种方法:

使用 'XMLHttpRequest' 对象发送 HTTP 请求:

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

// 设置请求方法和 URL
xhr.open('GET', 'https://api.example.com/data', true);

// 监听请求完成事件
xhr.onload = function() {
  if (xhr.status === 200) {
    // 请求成功
    console.log(xhr.responseText);
  } else {
    // 请求失败
    console.error('请求失败:' + xhr.status);
  }
};

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

使用 'fetch' API 发送 HTTP 请求:

fetch('https://api.example.com/data')
  .then(function(response) {
    if (response.ok) {
      // 请求成功
      return response.text();
    } else {
      // 请求失败
      throw new Error('请求失败:' + response.status);
    }
  })
  .then(function(data) {
    console.log(data);
  })
  .catch(function(error) {
    console.error(error);
  });

以上是使用 JavaScript 发送 HTTP 请求的两种常见方法。根据你的需要选择其中一种即可。

JavaScript 发送 HTTP 请求:XMLHttpRequest 与 Fetch API

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

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