如何在页面加载后从 url 中删除查询字符串

How can I remove the query string from the url after the page loads?

本文关键字:url 删除 查询 字符串 加载      更新时间:2023-09-26

我有一个附加了长查询字符串的URL。页面加载后,我不需要查询字符串。所以我想从地址栏中删除查询字符串而不重新加载页面。

我尝试了parent.location.hash = '';window.location.href = '/#'

他们没有区别。

正如其他人所说,您可以在现代浏览器(IE10+,FF4+,Chrome5 +(中使用History API执行此操作。答案中没有完整的示例,所以我想我会分享我的解决方案,因为我只是需要做同样的事情:

history.pushState(null, "", location.href.split("?")[0]);

如果您使用的是 Modernizr,您还可以检查历史记录 API 是否可用,如下所示:

if (Modernizr.history) {
    history.pushState(null, "", location.href.split("?")[0]);
}

这在使用历史 API 的现代浏览器中可以实现,但可能不是解决问题的最佳解决方案。

history.replaceState({}, 'some title', '/');

听起来您最好处理数据,然后重定向到主页,而不是直接返回HTML文档。

由于您不想保留URL,因此它对书签没有用,因此您最好发出POST请求。

这表明您应该使用 POST-Redirect-GET 模式。

如果不重新加载页面,您将无法做到这一点,想象一下是否可以在浏览器地址栏中放置您想要的任何内容?安全乐趣:)

虽然你现在可以使用新的历史 API 在 HTML5 中做到这一点(它仅适用于支持它的浏览器(,但实际上,你的方案最好是重写而不是包含它(似乎是大锤破解坚果(。

正如您所说,在页面加载后不需要查询字符串,您应该真正回发,然后在完成处理后重定向到另一个 URL。

window.history.replaceState(null, null, window.location.pathname);

使用 history.replaceState({}, "Title", "page.html");

pushState 的语法相同。但是,您必须找到一种方法来使IE理解这一点。

更好的方法是使用 Apache mod_rewrite模块。它非常易于使用。

我在个人项目中使用此代码截图,我需要在不重新加载的情况下删除 URL 参数:

var newURL = location.href.split("?")[0];
window.history.pushState('object', document.title, newURL);

我想再添加一种方法来做到这一点,特别是对于那些使用$routeProvider的人。

正如在其他一些答案中提到的,您可以使用:

var yourCurrentUrl = window.location.href.split('?')[0]; 
window.history.replaceState({}, '', yourCurrentUrl ); 

或者通过在历史记录堆栈中创建新记录:

window.history.pushState({}, '', yourCurrentUrl );  

有关使用history.pushStatehistory.replaceState的非常详细和很好的解释,您可以在SO上阅读这篇文章。

但是,如果您在应用程序中使用 Angular $routeProvider,那么如果它与任何现有模式匹配,它仍将捕获此更改。为避免这种情况,请确保您的$routeProvider将 reloadOnSearch 标志设置为 false,因为默认情况下它是 true

例如:

$routeProvider.when("/path/to/my/route",{
   controller: 'MyController',
   templateUrl: '/path/to/template.html',
   //Secret Sauce
   reloadOnSearch: false//Make sure this is explicitly set to false
});

更新的代码 现在它可以工作了

只需在要更改其链接的页面中添加以下代码即可。

// javascript function
   function buildLin(first) {
    var firs = first.toString()
       //alert(firs);
       //document.getElementById("team").value = "1";
           document.location.hash = "#" + firs.replace(/ /g, "_");
        //alert(document.location.hash);
    }
 //jQuery to call above function after page loads
  $(document).ready(function () {
      buildLin(2);
  });

不要忘记添加 http://code.jquery.com/jquery-latest.js 在您的页面上​

您可以通过使用 POST 而不是 GET 来完全避免查询字符串。