有没有一种方法可以在不重新加载页面的情况下修改当前页面的URL?

如果可能,我想访问#哈希之前的部分。

我只需要更改域之后的部分,所以我不会违反跨域策略。

 window.location.href = "www.mysite.com/page2.php";  // this reloads

当前回答

位置的任何更改(window.location或document.location)都将导致对新URL的请求,如果您不仅仅是更改URL片段。如果更改URL,则更改URL。

如果您不喜欢当前使用的URL,请使用服务器端URL重写技术,如Apache的mod_rewrite。

其他回答

在HTML5之前,我们可以使用:

parent.location.hash = "hello";

and:

window.location.replace("http:www.example.com");

此方法将重新加载页面,但HTML5引入了不应重新加载页面的history.pushState(page,caption,replace_url)。

在现代浏览器和HTML5中,有一种叫做pushState的窗口历史记录方法。这将更改URL并将其推送到历史记录中,而无需加载页面。

您可以这样使用它,它需要3个参数,1)状态对象2)标题和URL):

window.history.pushState({page: "another"}, "another page", "example.html");

这将更改URL,但不会重新加载页面。此外,它不会检查页面是否存在,因此如果您执行一些对URL做出反应的JavaScript代码,您可以这样处理它们。

此外,还有history.replaceState(),它做了完全相同的事情,只是它将修改当前历史,而不是创建新的历史!

此外,您还可以创建一个函数来检查history.pushState是否存在,然后执行以下操作:

function goTo(page, title, url) {
  if ("undefined" !== typeof history.pushState) {
    history.pushState({page: page}, title, url);
  } else {
    window.location.assign(url);
  }
}

goTo("another page", "example", 'example.html');

此外,您可以更改<HTML5浏览器的#,这不会重新加载页面。这是Angular根据标签进行SPA的方法。。。

更改#非常简单,比如:

window.location.hash = "example";

你可以这样检测:

window.onhashchange = function () {
  console.log("#changed", window.location.hash);
}

可以添加定位标记。我在我的网站上使用这个,这样我就可以通过Google Analytics跟踪人们在页面上访问的内容。

我只是添加了一个锚标记,然后添加了我要跟踪的页面部分:

var trackCode = "/#" + urlencode($("myDiv").text());
window.location.href = "http://www.piano-chords.net" + trackCode;
pageTracker._trackPageview(trackCode);

这是我的解决方案(newUrl是您要用当前URL替换的新URL):

history.pushState({}, null, newUrl);

下面是在不重新加载页面的情况下更改URL的功能。它仅支持HTML5。

  function ChangeUrl(page, url) {
        if (typeof (history.pushState) != "undefined") {
            var obj = {Page: page, Url: url};
            history.pushState(obj, obj.Page, obj.Url);
        } else {
            window.location.href = "homePage";
            // alert("Browser does not support HTML5.");
        }
    }

  ChangeUrl('Page1', 'homePage');