要使用 JavaScript 发出 HTTP 请求,可以使用内置的 fetch 函数或 XMLHttpRequest 对象。

使用 fetch 函数:

fetch(url, {
  method: 'GET', // 或者 'POST', 'PUT', 'DELETE' 等
  headers: {
    'Content-Type': 'application/json', // 根据需要设置其他头部
  },
  // 可选的请求体(比如 POST 请求时发送的数据)
  body: JSON.stringify(data),
})
.then(response => response.json()) // 将响应转换为 JSON 格式
.then(data => {
  // 处理响应数据
})
.catch(error => {
  // 处理错误
});

使用 XMLHttpRequest 对象:

const xhr = new XMLHttpRequest();
xhr.open('GET', url); // 或者 'POST', 'PUT', 'DELETE' 等
xhr.setRequestHeader('Content-Type', 'application/json'); // 根据需要设置其他头部
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    const response = JSON.parse(xhr.responseText); // 将响应转换为 JSON 格式
    // 处理响应数据
  } else {
    // 处理错误或其他状态
  }
};
// 可选的请求体(比如 POST 请求时发送的数据)
xhr.send(JSON.stringify(data));

以上代码示例是使用 GET 请求,如果需要使用其他 HTTP 方法,只需在 fetch 或 xhr.open 中指定相应的方法即可。

JavaScript 发出 HTTP 请求:fetch 和 XMLHttpRequest

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

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