使用 JavaScript 发出 HTTP 请求有多种方式,其中最常见的是使用内置的 XMLHttpRequest 对象或者 fetch 函数。下面是使用这两种方法之一发出 HTTP 请求的示例:

使用 XMLHttpRequest 对象:

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

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

// 监听请求状态变化事件
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    // 请求成功,可以处理返回的数据
    var response = xhr.responseText;
    console.log(response);
  }
};

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

使用 fetch 函数:

// 发起 GET 请求
fetch('http://example.com/api')
  .then(function(response) {
    if (response.ok) {
      // 请求成功,返回一个解析后的 Promise 对象
      return response.json();
    } else {
      throw new Error('请求失败');
    }
  })
  .then(function(data) {
    // 处理返回的数据
    console.log(data);
  })
  .catch(function(error) {
    console.log(error);
  });

请注意,这些示例是基本的 GET 请求示例,如果需要发送其他类型的请求(如 POST、PUT 等),则需要相应地设置请求头和请求体。

JavaScript HTTP 请求:XMLHttpRequest 和 Fetch API

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

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