使用 JavaScript 发送 HTTP 请求可以使用内置的 'XMLHttpRequest' 对象或 'fetch()' 函数。以下是使用这两种方法发送 GET 请求的示例代码:

使用 'XMLHttpRequest':

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

// 设置请求方法和 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);
  }
};

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

使用 'fetch()':

// 发送 GET 请求并处理响应
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));

请注意,这只是发送 GET 请求的简单示例。如果您需要发送其他类型的请求,例如 POST 请求或使用特定的参数和请求体,请参考相关文档以获取更多详细信息。

JavaScript 发送 HTTP 请求:XMLHttpRequest 和 fetch API

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

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