更改URL参数而不刷新页面

时间:2019-01-16 17:42:47

标签: javascript jquery

我一直试图在不重新加载网站的情况下更改URL的参数,但是,我不确定100%我的代码有什么问题。 URL中发生的事情是删除所有参数,并将其替换为简单的字符串。 即 http://localhost:50754/Signup555

我想从http://localhost:50754/Signup?A=1&B=2&C=3更改为http://localhost:50754/Signup?A=1&B=2&C=6

  function changeQueryString(searchString, documentTitle) {
        documentTitle = typeof documentTitle !== 'Pid' ? documentTitle : document.title;
        var urlSplit = (window.location.href).split("?");
        var obj = {
            Title: documentTitle,
            Url: urlSplit[0] + searchString
        };
        history.pushState(obj, obj.Title, obj.Url);
    }

<a onclick="changeQueryString('555', 'Pid')"> change it</a>

谢谢。

2 个答案:

答案 0 :(得分:0)

您可以使用“路由器”库。 Navigo是一个很好的例子。

答案 1 :(得分:0)

您的功能应该是:

  function changeQueryString(searchString, documentTitle) {
     window.history.replaceState(null, null, window.location.pathname+"?A="+searchString[0]+"&B="+searchString[1]+"&C="+searchString[2]);
    }

<a onclick="changeQueryString('555', 'Pid')"> change it</a>