我知道这个问题之前已经被问过很多次了,但是答案不够详细,无法解决我的问题。我不想更改页面的整个 URL。我想在不刷新的情况下单击按钮时附加参数 &item=brand
。
使用 document.location.search += '&item=brand';
使页面刷新。
使用 window.location.hash = "&item=brand";
附加而不刷新,但使用散列 #
消除参数的用法/效果。我尝试在添加后删除散列,但没有成功。
This answer许多其他人建议使用 HTML5 History API,特别是 history.pushState
方法,对于旧浏览器是设置片段标识符以防止页面重新加载。但是如何呢?
假设 URL 是:http://example.com/search.php?lang=en
如何使用 HTML5 pushState 方法或片段标识符附加 &item=brand
,以便输出如下所示:http://example.com/search.php?lang= en&item=brand
没有页面刷新?
我希望有人可以阐明如何使用 HTML5 pushState 将参数附加到现有/当前 URL。或者如何为相同目的设置片段标识符。一个很好的教程、演示或一段带有一点解释的代码会很棒。
Demo到目前为止我所做的。非常感谢您的回答。
最佳答案
您可以使用 pushState或 replaceState方法,即:
window.history.pushState("object or string", "Title", "new url");
或
window.history.replaceState(null, null, "?arg=123");
带参数的例子:
var refresh = window.location.protocol + "//" + window.location.host + window.location.pathname + '?arg=1';
window.history.pushState({ path: refresh }, '', refresh);
关于javascript - 在不刷新的情况下将参数附加到 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32828160/