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

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

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

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

当前回答

这现在可以在Chrome、Safari、Firefox 4+和Internet Explorer 10pp4+中完成!

有关详细信息,请参阅此问题的答案:使用新的URL更新地址栏,而无需哈希或重新加载页面

例子:

 function processAjaxData(response, urlPath){
     document.getElementById("content").innerHTML = response.html;
     document.title = response.pageTitle;
     window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", urlPath);
 }

然后,您可以使用window.onpopstate检测后退/前进按钮导航:

window.onpopstate = function(e){
    if(e.state){
        document.getElementById("content").innerHTML = e.state.html;
        document.title = e.state.pageTitle;
    }
};

有关操纵浏览器历史的更深入了解,请参阅MDN文章。

其他回答

下面是在不重新加载页面的情况下更改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');

您的新url。

let newUrlIS =  window.location.origin + '/user/profile/management';

在某种意义上,调用pushState()类似于设置window.location=“#foo”,因为两者都会创建并激活与当前文档相关的另一个历史条目。但是pushState()有一些优点:

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

您可以签出根目录:https://developer.mozilla.org/en-US/docs/Web/API/History_API

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

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

这现在可以在Chrome、Safari、Firefox 4+和Internet Explorer 10pp4+中完成!

有关详细信息,请参阅此问题的答案:使用新的URL更新地址栏,而无需哈希或重新加载页面

例子:

 function processAjaxData(response, urlPath){
     document.getElementById("content").innerHTML = response.html;
     document.title = response.pageTitle;
     window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", urlPath);
 }

然后,您可以使用window.onpopstate检测后退/前进按钮导航:

window.onpopstate = function(e){
    if(e.state){
        document.getElementById("content").innerHTML = e.state.html;
        document.title = e.state.pageTitle;
    }
};

有关操纵浏览器历史的更深入了解,请参阅MDN文章。

这就是无需重新加载即可导航的全部内容

//添加设置而不重新加载location.hash=“设置”;//如果url随哈希更改,请执行某些操作window.addEventListener('hashchange',()=>{console.log('rl哈希已更改!');});//如果url更改,请执行某些操作(不要使用哈希检测更改)//window.addEventListener('locationchange',function(){//console.log('rl已更改!');//})//删除#设置而不重新加载history.back();