使用 JavaScript 发出 HTTP 请求可以使用内置的 XMLHttpRequest 对象或者使用现代的 Fetch API。

使用 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 API:

// 发起 GET 请求
fetch('https://api.example.com/data')
  .then(function(response) {
    if (response.ok) {
      return response.json();
    }
    throw new Error('Network response was not ok.');
  })
  .then(function(data) {
    console.log(data);
  })
  .catch(function(error) {
    console.log('Error:', error.message);
  });

// 发起 POST 请求
fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    key: 'value'
  })
})
  .then(function(response) {
    if (response.ok) {
      return response.json();
    }
    throw new Error('Network response was not ok.');
  })
  .then(function(data) {
    console.log(data);
  })
  .catch(function(error) {
    console.log('Error:', error.message);
  });

请记住,在实际场景中,您需要根据您的具体需求配置请求头和请求体,并根据响应进行适当的处理。

JavaScript HTTP 请求:XMLHttpRequest 和 Fetch API 教程

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

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