javascript - 从 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 和路径添加到您的url
参数中history.pushState
:
let url = new URL(window.location.href);
history.pushState({}, null, url.origin + url.pathname);
使用history,您也可以只使用相对 url:
let url = new URL(window.location.href);
history.pushState({}, null, url.pathname);
另请参阅URL 构造函数(您已在示例中使用)。
您的原始代码不起作用的原因是url
inhistory.pushState()
是可选的,并且空字符串''
是虚假的。因此,在您的情况下,由于未使用真实值指定此参数,因此将其设置为文档的当前 URL。
推荐阅读
- html - 带有粘性导航栏的 Bootstrap Scroll Spy 无法按预期工作
- c++ - 成员函数无法访问 C++ 私有成员变量
- javascript - 如何在 SSR nuxt.js 中的 asyncData() 中统一处理 axios 错误
- r - 如何单独更改 ggplot 中选择的几个轴标签的小数位?
- java - 使用 MariaDB 10.4 和 eclipselink 的 java @GeneratedValue (strategy = GenerationType.IDENTITY) 问题
- c++ - 需要帮助解决未处理的异常错误
- python - Python中文件对话框的自动应答
- if-statement - 获取行中的第一个非空单元格
- java - 错误记录器和验证认证 java
- python - 是否有将属性应用于类的迭代方法?