fetch(url?key=value)
发起请求,通过.then处理响应;XMLHttpRequest需实例化对象,设置open和onload方法,注意参数需用encodeURIComponent编码,异步回调处理数据。
在JavaScript中发起GET请求是前端开发中的常见需求,主要用于从服务器获取数据,以下是几种主流方法的详细说明及示例代码,帮助开发者根据场景选择合适的方式。
XMLHttpRequest
是早期浏览器提供的API,兼容性良好。
// 创建XMLHttpRequest对象 const xhr = new XMLHttpRequest(); // 定义请求方法和URL xhr.open('GET', 'https://api.example.com/data?param1=value1¶m2=value2', true); // 设置请求完成后的回调 xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { const response = JSON.parse(xhr.responseText); console.log('请求成功:', response); } else { console.error('请求失败:', xhr.statusText); } }; // 处理网络错误 xhr.onerror = function() { console.error('网络错误'); }; // 发送请求 xhr.send();
注意事项:
encodeURIComponent
对URL参数编码,避免特殊字符问题。现代浏览器推荐使用fetch
,语法更简洁且支持Promise。
// 定义请求URL const url = 'https://api.example.com/data?param1=value1'; // 发起GET请求 fetch(url) .then(response => { if (!response.ok) { throw new Error(`HTTP错误: ${response.status}`); } return response.json(); // 解析JSON数据 }) .then(data => console.log('请求成功:', data)) .catch(error => console.error('请求失败:', error));
优势:
async/await
)。credentials: 'include'
配置。Axios是一个流行的HTTP库,支持浏览器和Node.js环境。
// 安装Axios后引入 import axios from 'axios'; // 发起GET请求 axios.get('https://api.example.com/data', { params: { param1: 'value1', param2: 'value2' } // 自动处理参数编码 }) .then(response => console.log('请求成功:', response.data)) .catch(error => console.error('请求失败:', error));
特点:
如果项目中已引入jQuery,可使用$.ajax
或$.get
简化代码。
// 使用$.get方法 $.get('https://api.example.com/data', { param1: 'value1' }, function(data) { console.log('请求成功:', data); }).fail(function(error) { console.error('请求失败:', error.statusText); });
参数编码
URL中的查询参数需通过encodeURIComponent
处理,避免特殊字符(如空格、&
)导致错误。
const param = encodeURIComponent('特殊字符&测试'); const url = `https://api.example.com/data?param=${param}`;
缓存问题
浏览器可能缓存GET请求结果,可通过添加时间戳或随机参数避免:
const url = `https://api.example.com/data?timestamp=${Date.now()}`;
安全性
GET请求的参数暴露在URL中,敏感数据需使用POST请求或通过Headers传递。
fetch
,语法现代且支持Promise。XMLHttpRequest
或jQuery。引用来源:
MDN Web Docs – Fetch API
Axios官方文档