JavaScript发送HTTP请求: 从Fetch到XMLHttpRequest

想要用JavaScript发送HTTP请求?你有两种选择: 现代的Fetch API和传统的XMLHttpRequest对象。本文将带你了解这两种方法,并提供实际示例,帮助你轻松掌握JavaScript网络请求。

使用Fetch API

Fetch API是现代JavaScript中发送HTTP请求的首选方式。它简洁易用,基于Promise,更适合异步操作。

发送GET请求javascriptfetch('https://api.example.com/data') .then(response => response.json()) .then(data => { // 处理响应数据 console.log(data); }) .catch(error => { // 处理错误 console.error('Error:', error); });

发送POST请求javascriptfetch('https://api.example.com/data', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ key: 'value' }),}) .then(response => response.json()) .then(data => { // 处理响应数据 console.log(data); }) .catch(error => { // 处理错误 console.error('Error:', error); });

使用XMLHttpRequest对象

XMLHttpRequest是较早的发送HTTP请求的方法,它提供了更细粒度的控制,但在某些情况下使用起来可能更复杂。

发送GET请求javascriptconst xhr = new XMLHttpRequest();xhr.open('GET', 'https://api.example.com/data');xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { const data = JSON.parse(xhr.responseText); // 处理响应数据 console.log(data); } else { // 处理错误 console.error('Error:', xhr.status); } }};xhr.send();

发送POST请求javascriptconst xhr = new XMLHttpRequest();xhr.open('POST', 'https://api.example.com/data');xhr.setRequestHeader('Content-Type', 'application/json');xhr.onreadystatechange = function() { // ... 处理响应 (类似GET请求)};xhr.send(JSON.stringify({ key: 'value' }));

注意事项

  • 以上示例中的URL和数据仅供参考,请替换为实际的URL和数据。* 请务必处理错误,并在实际应用中进行适当的错误处理。* 选择Fetch API还是XMLHttpRequest取决于你的具体需求和项目环境。Fetch API更现代,但XMLHttpRequest提供了更细致的控制。

希望这篇文章能帮助你理解如何使用JavaScript发送HTTP请求!

JavaScript发送HTTP请求: 从Fetch到XMLHttpRequest

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

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