JavaScript发送HTTP请求指南:从 XMLHttpRequest 到 Fetch API

想要在JavaScript中与服务器交互、获取数据或发送信息?你需要掌握HTTP请求的发送方法。本文将为你详细介绍两种常用的发送HTTP请求的方式:传统的XMLHttpRequest对象和现代的Fetch API。

使用XMLHttpRequest发送HTTP请求

XMLHttpRequest对象是 AJAX 技术的核心,允许你无需刷新页面即可与服务器交互。

1. 发送GET请求

以下代码演示了如何使用XMLHttpRequest发送GET请求:javascriptconst xhr = new XMLHttpRequest();xhr.open('GET', 'https://api.example.com/data', true);

xhr.onload = function() { if (xhr.status === 200) { const response = JSON.parse(xhr.responseText); console.log(response); }};

xhr.send();

这段代码执行了以下步骤:

  • 创建一个XMLHttpRequest对象。- 使用open()方法初始化请求,指定请求方法(GET)、请求URL和是否异步(true)。- 设置onload事件处理程序,在请求成功完成时处理响应。- 使用send()方法发送请求。

2. 发送POST请求

发送POST请求与GET请求类似,只是需要设置请求头和发送数据:javascriptconst xhr = new XMLHttpRequest();xhr.open('POST', 'https://api.example.com/data', true);xhr.setRequestHeader('Content-Type', 'application/json');

xhr.onload = function() { if (xhr.status === 200) { const response = JSON.parse(xhr.responseText); console.log(response); }};

const data = { name: 'John Doe', age: 30};

xhr.send(JSON.stringify(data));

在这里,我们使用setRequestHeader()方法设置Content-Type请求头,并使用send()方法发送JSON格式的数据。

使用Fetch API发送HTTP请求

Fetch API 提供了一种更简洁、更现代的发送HTTP请求的方式,它基于Promise,使得代码更易于阅读和维护。

1. 发送GET请求

使用fetch发送GET请求非常简单:javascriptfetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.log(error));

fetch()函数返回一个Promise,可以使用.then()方法处理成功响应,使用.catch()方法处理错误。

2. 发送POST请求

发送POST请求需要在fetch函数中传递一个包含请求方法、请求头和请求体的配置对象:javascriptconst data = { name: 'John Doe', age: 30};

fetch('https://api.example.com/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data)}) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.log(error));

总结

本文介绍了使用XMLHttpRequest和Fetch API发送HTTP请求的方法,并提供了代码示例。Fetch API由于其简洁性和基于Promise的特性,正逐渐成为发送HTTP请求的首选方式,但XMLHttpRequest仍然是理解HTTP请求工作原理的基础。选择哪种方法取决于你的项目需求和个人偏好。


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

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