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

Hyperscript按钮+Fetch请求:新标签页跳转变量解析问题求助

问题:Hyperscript中go to url无法识别变量result

我希望实现一个具备以下行为的按钮:

  • 用户点击后向后端发送请求
  • 后端返回一个链接
  • 在新标签页打开该链接

我编写了如下代码:

<button _="on click fetch '{% url 'some_api' movie.id %}' then
           log result then
           go to url result in new window">
Go to movie
</button>

但Hyperscript无法识别result为变量,直接重定向到http://localhost:8000/result,尽管log result命令能在控制台显示正确的链接。

更新:本例中movie.id并非固定为2499491,后端存在特定逻辑。


解决方法

问题出在Hyperscript的go to url语法上:当使用变量作为URL时,必须用**花括号{}**包裹变量,否则它会把result当作字面量字符串处理。

修改后的代码如下:

<button _="on click fetch '{% url 'some_api' movie.id %}' then
           log result then
           go to url {result} in new window">
Go to movie
</button>

这样Hyperscript就会正确解析result变量的值,而不是把它当成固定字符串。

你也可以选择显式存储请求结果到变量后再使用,效果一致:

<button _="on click 
           set response to fetch '{% url 'some_api' movie.id %}' then
           log response then
           go to url {response} in new window">
Go to movie
</button>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 02:45:01