JavaScript发送HTTP请求实战指南:从 XMLHttpRequest 到 Fetch API
JavaScript发送HTTP请求实战指南:从 XMLHttpRequest 到 Fetch API
想要在网页上与服务器交互,发送 HTTP 请求是必不可少的环节。JavaScript 提供了多种方式发送 HTTP 请求,本文将重点介绍两种常用的方法:XMLHttpRequest 对象和 Fetch API。
使用 XMLHttpRequest 对象发送 HTTP 请求
XMLHttpRequest 对象是浏览器内置的对象,用于在后台与服务器交换数据。
**发送 GET 请求:**javascriptfunction sendGetRequest(url) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { var response = xhr.responseText; // 处理响应数据 } }; xhr.send();}
**发送 POST 请求:**javascriptfunction sendPostRequest(url, data) { var xhr = new XMLHttpRequest(); xhr.open('POST', url, true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { var response = xhr.responseText; // 处理响应数据 } }; xhr.send(JSON.stringify(data));}
使用 Fetch API 发送 HTTP 请求
Fetch API 提供了一种更简洁、更现代的发送 HTTP 请求的方式。
**发送 GET 请求:**javascriptfunction sendGetRequest(url) { fetch(url) .then(function(response) { if (response.ok) { return response.text(); } throw new Error('Network response was not ok.'); }) .then(function(data) { // 处理响应数据 }) .catch(function(error) { console.log('Error:', error.message); });}
**发送 POST 请求:**javascriptfunction sendPostRequest(url, data) { fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(function(response) { if (response.ok) { return response.text(); } throw new Error('Network response was not ok.'); }) .then(function(data) { // 处理响应数据 }) .catch(function(error) { console.log('Error:', error.message); });}
总结
本文介绍了使用 XMLHttpRequest 对象和 Fetch API 发送 GET 和 POST 请求的方法,并提供了示例代码,希望能帮助你快速掌握 JavaScript 发送 HTTP 请求的技巧。选择哪种方法取决于你的项目需求和个人偏好。
原文地址: https://www.cveoy.top/t/topic/Sie 著作权归作者所有。请勿转载和采集!