上一篇
场景引入:
小明最近接了个新需求——要提交用户选中的多个商品ID到后端,他抓耳挠腮:“这数组参数怎么通过AJAX传啊?直接params: { ids: [1,2,3] }
会不会报错?” 别急!今天我们就来彻底解决这个前端开发中的经典问题!💪
当需要传递?id=1&id=2
这类重复参数时:
// 传统URL拼接方式 const ids = [101, 102, 103]; let url = '/api/products?'; ids.forEach(id => url += `id=${id}&`); // 使用URLSearchParams(更优雅✨) const params = new URLSearchParams(); ids.forEach(id => params.append('id', id)); fetch(`/api/products?${params}`) .then(response => response.json())
后端接收(以Spring为例):
@GetMapping("/products") public List<Product> getProducts(@RequestParam List<Long> id) { // 直接接收为List }
当参数结构复杂时(比如对象数组),推荐用POST+JSON:
const cartItems = [ { sku: 'A1001', qty: 2 }, { sku: 'B2002', qty: 1 } ]; fetch('/api/checkout', { method: 'POST', headers: { 'Content-Type': 'application/json' // 关键头!🚨 }, body: JSON.stringify({ items: cartItems }) // 序列化数组 });
后端接收:
@PostMapping("/checkout") public void checkout(@RequestBody CheckoutRequest request) { // request.getItems() 获取List<CartItem> }
$.ajax({ url: '/api/delete', traditional: true, // 关键配置!🌟 data: { ids: [1, 2, 3] } });
axios.get('/api/search', { params: { tags: ['js', 'frontend'], paramsSerializer: params => qs.stringify(params, { arrayFormat: 'repeat' }) } }); // 生成URL:/api/search?tags=js&tags=frontend
const formData = new FormData(); formData.append('files', fileInput.files[0]); formData.append('tags', JSON.stringify(['urgent', 'review'])); // 数组需特殊处理 fetch('/api/upload', { method: 'POST', body: formData // 不要设置Content-Type头! });
?ids[]=1&ids[]=2
格式 _t=${Date.now()}
2025年最新实践:
现在主流框架(如React/Vue)推荐使用axios
或fetch
,配合ES6的模板字符串和展开运算符,代码更简洁:
// 优雅的参数合并方式 const baseParams = { page: 1, size: 20 }; const searchParams = { keywords: ['手机', '防水'] }; axios.get('/api/search', { params: { ...baseParams, ...searchParams } });
掌握这些技巧,从此AJAX传参再也不踩坑!🎯 快去试试吧~
本文由 徐丽 于2025-08-02发表在【云服务器提供商】,文中图片由(徐丽)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://vps.7tqx.com/wenda/512760.html
发表评论