【问题标题】:Update parameter of URL (without refresh)更新 URL 参数(不刷新)
【发布时间】:2020-07-30 22:07:19
【问题描述】:

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

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

这是我的网址,生成的:

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 的参数值有所了解。

【问题讨论】:

    标签: javascript url parameters updates


    【解决方案1】:

    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

    【讨论】:

      【解决方案2】:

      使用 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 ])

      【讨论】:

      • 这确实有效,但在测验的下一个问题上,当我对 'exp=' 执行相同操作时,它会删除 'age=45&'(exp= 之前的每个字符串)
      • 如果你需要一个活生生的例子,这里是我的测验链接:deusbot-trading.com/quiz
      • @GuillaumeTdlg 再次检查我的答案
      • 哇,非常感谢你,它工作得很好!唯一的问题是,当我在 exp 上选择另一个答案时,它会不断添加到 url,如下所示:deusbot-trading.com/quiz/…
      • 你应该发布他点击另一个答案背后的代码逻辑......我相信你也应该问另一个问题
      猜你喜欢
      • 2017-11-25
      • 2020-03-17
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-02
      相关资源
      最近更新 更多