繁体   English   中英

URL更新参数(不刷新)

[英]Update parameter of URL (without refresh)

我知道这是一个非常有记录的主题,但是经过数小时的研究后,我现在陷入了困境。 我正在做一个测验,当做出选择时,我想更新 URL 上的相应参数。

https://deusbot-trading.com/quiz/age=&exp=&asset=

这是我的 URL,生成:

let refresh = window.location.protocol + "//" + window.location.host + window.location.pathname + '?age=&exp=&asset=';    
window.history.replaceState({ path: refresh }, '', refresh);

当用户单击按钮时,我想更新此 url 的一些参数。 例如,我想在不更改 url 的 rest 的情况下为“年龄”分配一个值:

https://deusbot-trading.com/quiz/age=45+&exp=&asset=


我试过了:

window.history.replaceState({ 'age=', 'age=45+');

但这似乎不起作用。 我希望有人能对如何动态修改 URL 的参数值有所了解。

历史 API pushState plus searchparams

 let refresh = new URL("https://deusbot-trading.com/quiz/?age=45+&exp=&asset=") // new URL(location.href) const refreshObj = { "path": refresh } refresh.searchParams.set("age",50) console.log(refresh) // window.history.replaceState(refreshObj, '', refresh); // has to be on the same origin

使用 replaceState 你应该这样做:它会产生预期的结果

https://deusbot-trading.com/quiz/age=45+&exp=&asset=

在你应用这个之后

history.replaceState({}, null, location.href.replace('age=','age=45+'))

对于进一步的更改,只需以相同的方式继续:

history.replaceState({}, null, location.href.replace('exp=','exp=1000'))

笔记

影响 url 的唯一部分是第三个参数

history.replaceState(data, title [, url ])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM