如何在URL中正确设置动态搜索参数?语法正确性验证
问题
我在URL中设置动态搜索参数的方式是否正确?是否应该使用反引号或其他语法?我需要通过输入内容在后端URL端点中搜索对象。
代码示例:
people: [], getAllProducts(searchInput) { let searchUrl = searchInput; fetch(`http://test.mosvesna.com/?search=${searchUrl}`) .then((response) => response.json()) .then((res) => { let local = this; if (searchInput) { this.people = res.filter((i) => i.name.toLowerCase().includes(searchInput.toLowerCase())); } else { this.people = res; } }); }
回答
- 你用反引号(ES6模板字符串)拼接URL的语法是没问题的,但缺少URL编码处理——如果搜索输入里包含空格、
&、%这类特殊字符,会导致URL格式错误,后端无法正确解析参数。正确的做法是用encodeURIComponent()对搜索参数编码:
fetch(`http://test.mosvesna.com/?search=${encodeURIComponent(searchUrl)}`)
- 代码里还有两个可以优化的点:
- 你在后端返回数据后又做了一次前端过滤,这完全没必要——既然已经通过
search参数请求后端,应该让后端直接返回过滤后的结果,减少数据传输量和前端计算开销。 let local = this;是多余的,因为.then里用的是箭头函数,会自动绑定外层的this,直接用this就行。
- 你在后端返回数据后又做了一次前端过滤,这完全没必要——既然已经通过
优化后的代码示例:
people: [], getAllProducts(searchInput) { const url = searchInput ? `http://test.mosvesna.com/?search=${encodeURIComponent(searchInput)}` : 'http://test.mosvesna.com/'; fetch(url) .then(response => response.json()) .then(res => { this.people = res; }); }
内容的提问来源于stack exchange,提问作者user20984971
相关产品推荐
相关产品推荐

