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

dojqjjoe  于 2022-12-02  发布在  其他
关注(0)|答案(9)|浏览(155)

我有一个附加了很长查询字符串的URL。加载页面后,我不需要查询字符串。因此,我希望在不重新加载页面的情况下从地址栏中删除查询字符串。
我试过parent.location.hash = '';window.location.href = '/#'
他们没有造成任何影响。

bnlyeluc

bnlyeluc1#

正如其他人所说,您可以在现代浏览器(IE10+、FF4+、Chrome5+)中使用History API来实现这一点。答案中没有完整的示例,所以我想分享我的解决方案,因为我只是有一个做同样事情的要求:

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

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

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

yyyllmsg2#

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

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

听起来,处理数据然后重定向到主页比直接返回HTML文档更好。
由于您不想保留URL,因此它对书签没有用处,因此很可能您最好发出POST请求。
这表明您应该使用POST-Redirect-GET pattern

kcugc4gi

kcugc4gi3#

如果不重新加载页面,你就无法做到这一点,想象一下,如果你可以在浏览器的地址栏中放置任何你想要的东西?

尽管您现在可以使用新的history API在HTML5(仅在支持它的浏览器上工作)中执行此操作,但实际上,您的场景最好重写,而不是包括它(似乎是大锤敲坚果)。

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

nx7onnlm

nx7onnlm4#

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

edqdpe6u5#

使用history.replaceState({}, "Title", "page.html");
pushState的语法相同。但是,您必须找到一种方法使IE理解这一点。
一个更好的方法是使用Apache mod_rewrite模块,它非常容易使用。

0qx6xfy6

0qx6xfy66#

我使用这个代码snippit在我的个人项目,我需要删除URL参数没有重新加载:

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

ki0zmccv7#

我想再添加一种方法来实现这一点,特别是对于使用$routeProvider的用户。
正如在其他一些答案中所提到的,您可以使用以下方法来实现此目的:

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

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

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

关于如何处理history.pushStatehistory.replaceState的详细说明,可以阅读this post on SO

但是,如果您在应用中使用Angular$routeProvider,则它仍会捕获此更改(如果它与任何现有模式匹配)。为了避免这种情况,请确保您的$routeProviderreloadOnSearch标志设置为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
});
dxpyg8gm

dxpyg8gm8#

更新的代码现在可以使用了

只需将下面的代码添加到要更改其链接的页面中。

// 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

vfh0ocws

vfh0ocws9#

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

相关问题