You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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;
        }
    });
  }

回答

  1. 你用反引号(ES6模板字符串)拼接URL的语法是没问题的,但缺少URL编码处理——如果搜索输入里包含空格、&、%这类特殊字符,会导致URL格式错误,后端无法正确解析参数。正确的做法是用encodeURIComponent()对搜索参数编码:
fetch(`http://test.mosvesna.com/?search=${encodeURIComponent(searchUrl)}`)
  1. 代码里还有两个可以优化的点:
    • 你在后端返回数据后又做了一次前端过滤,这完全没必要——既然已经通过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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 16:42:09