如何通过纯JavaScript发送HTTP请求?除XML、Ajax外是否有其他方式?
纯JavaScript发送HTTP请求的几种实现方式
嘿,很高兴能帮你解答这个问题!其实除了你查到的XMLHttpRequest(也就是常说的Ajax底层实现),现在还有更简洁的现代纯JS方案,我给你一一梳理:
1. 现代首选:Fetch API
这是ES6之后推出的标准浏览器API,完全原生纯JS,基于Promise设计,写法比XHR清爽太多,也是现在最推荐的方式。
GET请求示例
// 发起GET请求获取数据 fetch('https://api.example.com/data') .then(response => { // 先检查响应状态是否正常 if (!response.ok) { throw new Error(`请求失败,状态码:${response.status}`); } return response.json(); // 把响应解析成JSON格式 }) .then(data => { console.log('成功拿到数据:', data); // 这里可以处理数据,比如渲染到页面 }) .catch(error => { console.error('请求过程出错:', error); });
POST请求示例(发送JSON数据)
// 发起POST请求提交数据 fetch('https://api.example.com/submit', { method: 'POST', // 指定请求方法 headers: { 'Content-Type': 'application/json', // 告诉服务器请求体是JSON格式 }, body: JSON.stringify({ username: 'shahrzad', message: '这是测试提交的数据' }), // 把JS对象转成JSON字符串作为请求体 }) .then(response => response.json()) .then(result => { console.log('提交成功,服务器返回:', result); }) .catch(error => { console.error('提交出错:', error); });
Fetch API几乎支持所有现代浏览器,只有非常老旧的IE不兼容,如果不需要兼容IE的话,优先用它。
2. 传统兼容方案:XMLHttpRequest(XHR)
你提到的“XML相关实现”其实就是它,这是最早的纯JS异步请求方案,兼容性拉满(包括IE6+),不过代码相对繁琐一些。
GET请求示例
const xhr = new XMLHttpRequest(); // 初始化请求:方法、URL、是否异步(true为异步) xhr.open('GET', 'https://api.example.com/data', true); // 请求成功完成后的回调 xhr.onload = function() { // 状态码200-299表示请求成功 if (xhr.status >= 200 && xhr.status < 300) { const data = JSON.parse(xhr.responseText); console.log('获取到的数据:', data); } else { console.error('请求失败,状态码:', xhr.status); } }; // 网络请求出错的回调 xhr.onerror = function() { console.error('网络连接出错,请检查地址或网络状态'); }; // 发送请求 xhr.send();
POST请求示例(发送JSON数据)
const xhr = new XMLHttpRequest(); xhr.open('POST', 'https://api.example.com/submit', true); // 设置请求头,告诉服务器我们发送的是JSON xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { const response = JSON.parse(xhr.responseText); console.log('提交成功,服务器返回:', response); } else { console.error('提交失败,状态码:', xhr.status); } }; xhr.onerror = function() { console.error('网络请求出错'); }; // 发送JSON格式的请求体 xhr.send(JSON.stringify({ username: 'shahrzad', email: 'shahrzad@example.com' }));
总结一下:如果项目不需要兼容老IE,Fetch API是最优解;如果要覆盖所有老旧浏览器,就用XMLHttpRequest。
内容的提问来源于stack exchange,提问作者Shahrzad Nazemi
相关产品推荐
相关产品推荐

