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

如何在JavaScript中使用动态参数发起fetch请求?

在JavaScript中使用动态参数发起fetch请求当然可以

下面是几种常用的实现方式:

  • 模板字符串(推荐):ES6的模板字符串语法可以直接嵌入变量,写法简洁直观:
const parameter1 = "posts";
const parameter2 = "1001";

fetch(`/api/${parameter1}/${parameter2}`)
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.error("请求失败:", err));
  • 字符串拼接:传统的字符串加法拼接方式,兼容所有ES版本:
const parameter1 = "posts";
const parameter2 = "1001";

fetch("/api/" + parameter1 + "/" + parameter2)
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.error("请求失败:", err));
  • URL构造函数(适合复杂场景):如果参数包含特殊字符(比如空格、问号),用URL构造函数配合编码处理能避免解析错误,更安全:
const parameter1 = "user name";
const parameter2 = "article?tag=js";

fetch(`/api/${encodeURIComponent(parameter1)}/${encodeURIComponent(parameter2)}`)
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.error("请求失败:", err));

额外注意:如果参数可能包含/、?、&这类URL特殊字符,一定要用encodeURIComponent()对参数单独编码,防止路径结构被破坏。

内容的提问来源于stack exchange,提问作者Sapir Hender

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:20:41