javascript - 在不刷新的情况下将参数附加到 URL

标签 javascript jquery html pushstate html5-history

我知道这个问题之前已经被问过很多次了,但是答案不够详细,无法解决我的问题。我不想更改页面的整个 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到目前为止我所做的。非常感谢您的回答。

最佳答案

您可以使用 pushStatereplaceState方法,即:

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/

相关文章:

javascript - jquery ajax 提交表单似乎不使用 Ajax 路由,因为 XHR 为空

javascript - 如何防止按钮第二次点击事件

javascript - 油猴劫持 setInterval

javascript - 谷歌应用程序脚本 - 表单不会自动邮寄电子表格响应

javascript - 单击复选框时无法发出事件。 (socket.io)

javascript - 在js中使用传递的val

javascript - 打开动态高度时延迟加载会切断图像高度

python - 如何将 XML 放入 HTML 模板中? python /Django

javascript - Div 占用了它不存在的空间

javascript - Amazon S3 奇怪的 CORS 行为 : No 'Access-Control-Allow-Origin' header is present on the requested resource