在JavaScript中发送GET请求主要有fetch API、XMLHttpRequest和jQuery的$.ajax方法三种方式,以下是具体实现方法及示例:
1. 使用Fetch API(现代JavaScript首选)Fetch API是现代JavaScript中发送GET请求的简洁且强大的方式,支持Promise,代码易读且易于维护。
fetch('https://api.example.com/data'
) .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => console.log(data)) .catch(error => console.error('Error:', error));- 带查询参数的GET请求:使用URLSearchParams构建查询字符串,使代码更清晰。
const params = new URLSearchParams({ name: 'John', age: 30});fetch(`https://api.example.com/data?
${params.toString()}`) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));- 优点:语法简洁,支持Promise,适合现代浏览器。
- 缺点:对旧浏览器兼容性较差(需polyfill)。
2. 使用XMLHttpRequest(兼容旧项目)XMLHttpRequest适用于需要兼容旧浏览器或需要更细粒度控制的场景,但代码较复杂。
const xhr = new XMLHttpRequest();xhr.open('GET', 'https://api.example.com/data'
, true);xhr.onload = function() { if (xhr.status === 200) { console.log(JSON.parse(xhr.responseText)); } else { console.error('Error:', xhr.statusText); }};xhr.onerror = function() { console.error('Network Error');};xhr.send();const params = new URLSearchParams({ name: 'John', age: 30}).toString();const xhr = new XMLHttpRequest();xhr.open('GET', `https://api.example.com/data?
${params}`, true);xhr.onload = function() { if (xhr.status === 200) { console.log(JSON.parse(xhr.responseText)); }};xhr.send();- 优点:兼容所有现代浏览器和旧浏览器。
- 缺点:需手动处理状态码和错误,代码冗长。
3. 使用jQuery的$.ajax方法(简化开发)若项目已使用jQuery,$.ajax可简化请求发送,封装了细节处理。
$.ajax({ url: 'https://api.example.com/data'
, type: 'GET', success: function(data) { console.log(data); }, error: function(xhr, status, error) { console.error('Error:', error); }});- 带查询参数的GET请求:通过data选项传递参数。
$.ajax({ url: 'https://api.example.com/data'
, type: 'GET', data: { name: 'John', age: 30 }, success: function(data) { console.log(data); }});- 优点:语法简单,封装了错误处理和参数拼接。
- 缺点:需引入jQuery库,增加项目依赖。
常见问题及解决方案function handleResponse(data) { console.log(data);}const script = document.createElement('script');script.src = 'https://api.example.com/data?callback=handleResponse';document.body.appendChild
(script);- 性能优化:
缓存:利用浏览器对GET请求的缓存机制。
节流/防抖:频繁请求时使用技术减少请求次数。
总结- 首选Fetch API:适用于现代项目,语法简洁。
- 选择XMLHttpRequest:需兼容旧浏览器或精细控制时。
- 使用jQuery:项目已依赖jQuery时简化开发。
根据项目需求和环境选择合适的方法,可提升代码效率和可维护性。