JavaScript发送HTTP请求: XMLHttpRequest和Fetch API详解
JavaScript发送HTTP请求: XMLHttpRequest和Fetch API详解
在现代Web开发中,使用JavaScript发送HTTP请求是与后端服务交互、获取数据和构建动态Web应用的关键技能。本文将深入探讨两种常用的发送HTTP请求的方法:XMLHttpRequest和Fetch API。
1. 使用XMLHttpRequest发送HTTP请求
XMLHttpRequest对象是浏览器提供的用于在后台发送HTTP请求的原生API。它允许你以异步的方式发送请求,并在请求完成时接收响应。
以下是使用XMLHttpRequest发送HTTP请求的示例代码:javascriptfunction sendHttpRequest(url, method, data, callback) { var xhr = new XMLHttpRequest(); xhr.open(method, url, true);
xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200) { callback(null, xhr.responseText); } else { callback(new Error('HTTP request failed with status ' + xhr.status)); } } };
xhr.send(data);}
// 示例用法var url = 'https://api.example.com/data';var method = 'POST';var data = JSON.stringify({ key: 'value' });
sendHttpRequest(url, method, data, function(error, response) { if (error) { console.error('HTTP request failed', error); } else { console.log('HTTP response received', response); }});
代码解析:
- 创建
XMLHttpRequest对象: 使用new XMLHttpRequest()创建一个新的XMLHttpRequest对象。2. 打开请求: 使用open()方法初始化请求,传入请求方法(如'GET'、'POST')、请求URL和是否异步(true表示异步)。3. 监听状态变化: 设置onreadystatechange事件监听函数,在请求状态发生变化时触发。4. 处理响应: 在onreadystatechange事件中,检查readyState属性是否为4(请求完成)和status属性是否为200(请求成功),如果是,则调用回调函数并传入响应数据。5. 发送请求: 使用send()方法发送请求,如果需要发送数据,则将其作为参数传入。
2. 使用fetch API发送HTTP请求
fetch API是现代浏览器提供的更简洁、更易于使用的发送HTTP请求的API。它返回一个Promise对象,可以方便地使用链式调用处理响应。
以下是使用fetch API发送HTTP请求的示例代码:javascriptfunction sendHttpRequest(url, method, data, callback) { fetch(url, { method: method, body: data }) .then(function(response) { if (!response.ok) { throw new Error('HTTP request failed with status ' + response.status); } return response.text(); }) .then(function(responseText) { callback(null, responseText); }) .catch(function(error) { callback(error); });}
// 示例用法var url = 'https://api.example.com/data';var method = 'POST';var data = JSON.stringify({ key: 'value' });
sendHttpRequest(url, method, data, function(error, response) { if (error) { console.error('HTTP request failed', error); } else { console.log('HTTP response received', response); }}
原文地址: https://www.cveoy.top/t/topic/SVq 著作权归作者所有。请勿转载和采集!