将参数附加到URL而不刷新

Min*_*lla 33 javascript jquery html5 pushstate html5-history

我知道之前已经多次询问过,但答案的描述性不足以解决我的问题.我不想更改页面的整个URL.我想&item=brand在按钮点击时追加一个参数而不刷新.

使用document.location.search += '&item=brand';使页面刷新.

使用window.location.hash = "&item=brand";append而不刷新但使用散列#来消除参数的使用/效果.我试图在追加后删除散列,但这不起作用.


这个答案和许多其他人建议使用HTML5 History API,特别是history.pushState方法,对于旧浏览器,是设置片段标识符以防止页面重新加载.但是怎么样?


假设URL是: http://example.com/search.php?lang=en

如何&item=brand使用HTML5 pushState方法或片段标识符进行追加,以便输出如下:http://example.com/search.php?lang=en&item=brand没有页面刷新?


我希望有人可以说明如何使用HTML5 pushState将参数附加到现有/当前URL.或者,如何为相同目的设置片段标识符.一个很好的教程,演示或一段代码与一点点解释将是伟大的.

演示到目前为止我所做的一切.非常感谢您的回答.

Ped*_*ito 59

您可以使用pushStatereplaceState方法,即:

window.history.pushState("object or string", "Title", "new url");
Run Code Online (Sandbox Code Playgroud)

要么

window.history.replaceState(null, null, "/another-new-url");
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,我最终使用window.history.replaceState(null,null,"?mock"); 添加url param而不重新加载. (4认同)

pab*_*nes 15

如果有人想要将参数添加到更复杂的URL(我的意思是,https://stackoverflow.com/questions/edit?newParameter = 1),以下代码对我有用:

var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?newParameter=1';
window.history.pushState({ path: newurl }, '', newurl);
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!


小智 12

如果您想同时添加和删除参数,也可以使用 URL API:

const url = new URL(window.location.href);
url.searchParams.set('param1', 'val1');
url.searchParams.delete('param2');
window.history.replaceState(null, null, url); // or pushState
Run Code Online (Sandbox Code Playgroud)