将参数附加到URL而不刷新
我知道之前已经多次询问过,但答案的描述性不足以解决我的问题。 我不想更改页面的整个URL。 我想在按钮点击时追加参数&item=brand
而不刷新。
使用document.location.search += '&item=brand';
使页面刷新。
使用window.location.hash = "&item=brand";
追加而不刷新,但使用散列#
,消除了参数的用法/效果。 我试图在追加后删除散列,但这不起作用。
这个答案和许多其他人建议使用HTML5 History API,特别是history.pushState
方法,而对于旧浏览器则是设置片段标识符以防止页面重新加载。 但是怎么样?
假设URL为: http://example.com/search.php?lang=en
: http://example.com/search.php?lang=en
如何使用HTML5 pushState方法或片段标识符附加&item=brand
以便输出如下: http://example.com/search.php?lang=en&item=brand
: http://example.com/search.php?lang=en&item=brand
?lang &item=brand
en &item=brand
没有页面刷新?
我希望有人可以说明如何使用HTML5 pushState将参数附加到现有/当前URL。 或者,如何为相同目的设置片段标识符。 一个很好的教程,演示或一段代码与一点点解释将是伟大的。
演示到目前为止我所做的一切。 非常感谢您的回答。
您可以使用pushState或replaceState方法,即:
window.history.pushState("object or string", "Title", "new url");
要么
window.history.replaceState(null, null, "/another-new-url");
如果有人想将参数添加到更复杂的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);
希望这可以帮助!