history.pushState如何摆脱get参数?

时间:2014-11-19 10:35:58

标签: javascript html5 browser-history pushstate

我正在使用

  history.pushState('id','myTitle','myURL');

操纵显示的URL和历史堆栈。 在某些时候我推动获取参数如下:

history.pushState('id','myTitle','?mySubLinkedStuff=hotSubLinkedStuff');

现在我做的时候

history.pushState('id','myTitle','#justSomeHashtag');

它产生http://example.com?mySubLinkedStuff=hotSubLinkedStuff#justSomeHashtag 我也可以覆盖mySubLinkedStuff的值,但似乎无法完全获得它的rif。

期望的结果:

http://example.com#justSomeHashtaghttp://example.com/#justSomeHashtag

显然我不想在服务器上进行整个往返,我也想避免使用绝对路径或URL来保持项目的可移植性。

2 个答案:

答案 0 :(得分:0)

正如NimrodArgov正确评论的那样:覆盖现有的get-parameter字符串就可以了 推送完整的URL。 因此,为了确保应用程序的可移植性(使其在各个域上可用),我这样做了:

history.statePush(document.location.origin + window.location.pathname + '#myHashValue');

完美无缺地工作。

答案 1 :(得分:0)

在没有GET参数的情况下推送当前地址:

history.pushState("id", "myTitle", 
  location.protocol + "//" + location.host +
  location.pathname + location.hash
);

除此之外;

要推送哈希更改,我可以这样做:

history.pushState("id", "myTitle", 
  location.protocol + "//" + location.host +
  location.pathname + location.search + "#myHashHere"
);

要推送查询更改,我可以这样做:

history.pushState("id", "myTitle", 
  location.protocol + "//" + location.host +
  location.pathname + "?my=query&over=here" + location.hash
);

※对不起,我没有足够的业力来评论Max’s answer ...:/

相关问题