update parameters in URL with history.pushState()

2019-03-24 15:32发布

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 is my list of query params.

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,foo1&param2=bar&param3=another_foo

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) ?

2条回答
Anthone
2楼-- · 2019-03-24 16:15

This function might be helpful

function updateUrlParameter(param, value) {
    const regExp = new RegExp(param + "(.+?)(&|$)", "g");
    const newUrl = window.location.href.replace(regExp, param + "=" + value + "$2");
    window.history.pushState("", "", newUrl);
}

Edit: The following solution is simpler, and it also works if the parameter is not yet part of the URL. However, it's not supported by Internet Explorer (you don't say?).

function setQueryStringParameter(name, value) {
    const params = new URLSearchParams(location.search);
    params.set(name, value);
    window.history.replaceState({}, "", decodeURIComponent(`${location.pathname}?${params}`));
}
查看更多
Juvenile、少年°
3楼-- · 2019-03-24 16:38

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

var pageUrl = '?' + queryString;
window.history.pushState('', '', pageUrl);
查看更多
登录 后发表回答