在 JavaScript 中,你可以使用内置的 XMLHttpRequest 对象或者使用现代的 fetch 函数来发出 HTTP 请求。

使用 XMLHttpRequest 对象的示例:

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

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

// 可选:设置请求头
xhr.setRequestHeader('Content-Type', 'application/json');

// 可选:设置响应类型
xhr.responseType = 'json';

// 监听请求状态的变化
xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      // 请求成功
      var response = xhr.response;
      console.log(response);
    } else {
      // 请求失败
      console.error('请求失败:' + xhr.status);
    }
  }
};

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

使用 fetch 函数的示例:

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

这些示例演示了如何发出一个简单的 GET 请求,但你可以根据需要使用不同的 HTTP 方法(例如 POST、PUT 等),并在请求中包含请求体数据。

JavaScript 发送 HTTP 请求:XMLHttpRequest 和 Fetch API

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

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