更新 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 的其余部分的情况下为 "age" 赋值:

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


我试过了:

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

但这似乎不起作用。 我希望有人可以阐明如何动态修改 URL.

的参数值

History API pushState 加上 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 ])