如何解决在不刷新页面的情况下从 url 中删除搜索查询?
我有一个简单的任务!我希望当我提交表单并获得表单的成功或错误消息时,我直接转到表单(使用锚点),因此为了这样做,我在 from action 的 URL 中添加了一个参数,如下所示:
action="%%url%%?form-submitted=true"
当表单提交时,我写了这段代码:
// This script is for moving the page to the form is the page is loaded by submitting the form
let pageUrl = window.location.href;
let url = new URL(pageUrl);
let formSubmitted = url.searchParams.get("form-submitted");
if(formSubmitted){
window.location.href = "#form-container";
}
代码运行良好,提交表单时我正在移动到我的表单,但是如果我滚动页面并查看幻灯片,例如,我决定刷新页面,则表单提交的参数是在 URL 中,所以刷新时我再次转到表单,这很不愉快。
为了解决这个问题,我必须在不刷新页面的情况下从 URL 中删除查询参数,我尝试了这个:
// This script is for moving the page to the form is the page is loaded by submitting the form
let pageUrl = window.location.href;
let url = new URL(pageUrl);
let formSubmitted = url.searchParams.get("form-submitted");
history.pushstate({},null,'');
if(formSubmitted){
window.location.href = "#form-container";
}
我只是保留了我的域和锚标记,但似乎什么也没发生。
解决方法
尝试仅将源网址和路径添加到 url
的 history.pushState
参数:
let url = new URL(window.location.href);
history.pushState({},null,url.origin + url.pathname);
使用 history,您也可以只使用相对网址:
let url = new URL(window.location.href);
history.pushState({},url.pathname);
另见 URL Constructor(您已在示例中使用)。
您的原始代码不起作用的原因是 url
中的 history.pushState()
是可选的,而空字符串 ''
是假的。因此,在您的情况下,由于此参数未指定为真值,因此它被设置为文档的当前 URL。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。