JavaScript 发起 HTTP 请求完全指南:从 XMLHttpRequest 到 Fetch API

在现代 Web 开发中,使用 JavaScript 发送 HTTP 请求是与服务器交互和构建动态应用的关键。本文将带你了解两种常用的 HTTP 请求方法:传统的 XMLHttpRequest 对象和更现代的 Fetch API

使用 XMLHttpRequest 对象

XMLHttpRequest 对象允许你通过 JavaScript 发送 HTTP 请求。以下是发送 GET 请求的基本步骤:

// 创建 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();

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

// 监听请求状态改变事件
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    // 请求已完成并成功
    var response = xhr.responseText;
    console.log(response);
  }
};

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

使用 Fetch API

Fetch API 提供了一种更简洁、更易于使用的发送 HTTP 请求的方式。

发送 GET 请求:

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

发送 POST 请求:

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

总结

以上代码演示了如何使用 XMLHttpRequestFetch API 发送 GET 和 POST 请求,并处理响应数据。你可以根据自己的需求修改和扩展这些示例,例如设置请求头、处理不同类型的响应数据等。

JavaScript 发起 HTTP 请求完全指南:从 XMLHttpRequest 到 Fetch API

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

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