使用history.pushState()更新URL中的参数 [英] update parameters in URL with history.pushState()

查看:893
本文介绍了使用history.pushState()更新URL中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用history.pushState在我的页面上进行AJAX调用后将几个参数附加到当前页面URL。现在,在基于用户操作的同一页面上,我想使用相同或更多的参数集再次更新页面URL。所以我的代码如下所示:

I am using history.pushState to append few params to current page URL after making an AJAX call on my page. Now on same page based on user action, I want to update the page URL again with same or additional set of params. So my code looks like this:

var pageUrl = window.location.href + "?" + queryString;
window.history.pushState('','',pageUrl);

queryString是我的查询参数列表。

queryString is my list of query params.

  • For example, My Default page URL: http://sample.com/
  • After First AJAX call on same page URL should be: http://sample.com?param1=foo&param2=bar
  • After Second AJAX call on same page URL can be: http://sample.com/?param1=foo,foo1&param2=bar&param3=another_foo

但是使用上面的代码我的params会被params附加到URL,在第二次AJAX调用后它们看起来如下所示:

But with the above code my params are getting appended to URL with the params and they look like below after second AJAX call:

http://sample.com?param1=foo&param2=bar&param1=foo,fo o1& param2 = bar& param3 = another_foo

所以params在URL中出现两次,是否有任何方法可以在推送之前替换URL中的params历史或任何其他更好的方法来实现这一点在javascript(jquery)?

So the params appear twice in the URL, is there any way of replacing the params in URL before pushing to History or any other better way to achieve this in javascript(jquery) ?

推荐答案

我认为你需要的是删除 window.location.href 并保留'?'+

I think what you need is remove window.location.href and leave '?' +.

var pageUrl = '?' + queryString;
window.history.pushState('', '', pageUrl);

这篇关于使用history.pushState()更新URL中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆