简体   繁体   English

如何在不重新加载页面的情况下更改 URL?

[英]How do I change the URL without reloading the page?

On two different pages I'm trying to change the URL without reloading the page.在两个不同的页面上,我试图在不重新加载页面的情况下更改 URL。 I also need the forward and back browser buttons to go to the original URL, not the new URL.我还需要前进和后退浏览器按钮才能转到原始 URL,而不是新 URL。

I created a switch to determine if I am on one of the pages which needs to change the URL.我创建了一个开关来确定我是否在需要更改 URL 的页面之一上。

And then I put together a snippet for changing the URL based on this this answer .然后我根据这个答案整理了一个用于更改 URL 的片段。 But this is where I'm stuck.但这就是我被困的地方。

Because I'm not sure how I should be calling processAjaxData , which I assume is where I pass in the new URL slug.因为我不确定我应该如何调用processAjaxData ,我认为这是我传入新 URL slug 的地方。 Also what should I be passing in for response ?另外我应该传递什么来response

<script>
var windowLoc = jQuery(location).attr('pathname'); //jquery format to get window.location.pathname
switch (windowLoc) {
  case "/the-old-url-I-want-to-change/":
    function processAjaxData(response, urlPath) {
      document.getElementByClass("page").innerHTML = response.html;
      document.title = response.pageTitle;
      window.history.pushState({"html": response.html, "pageTitle": response.pageTitle}, "", urlPath);
    }
    window.onpopstate = function(e) {
      if (e.state) {
        document.getElementByClass("page").innerHTML = e.state.html;
        document.title = e.state.pageTitle;
      }
    };
    break;
  case "/another-old-url-I-want-to-change/":
    function processAjaxData(response, urlPath) {
      document.getElementByClass("page").innerHTML = response.html;
      document.title = response.pageTitle;
      window.history.pushState({"html": response.html, "pageTitle": response.pageTitle}, "", urlPath);
    }
    window.onpopstate = function(e) {
      if (e.state) {
        document.getElementByClass("page").innerHTML = e.state.html;
        document.title = e.state.pageTitle;
      }
    };
    break;
}
</script>

If all you're actually trying to do is change the url, and you don't mind the page reloading when the user clicks the back button, then you can remove most of the example code.如果您实际要做的只是更改 url,并且您不介意在用户单击后退按钮时重新加载页面,那么您可以删除大部分示例代码。 The only part of this whole business that you need is the pushstate.您需要的整个业务的唯一部分是 pushstate。 So just pull that out and place it directly in your switch.因此,只需将其拉出并直接放入您的开关中即可。 Something like:就像是:

<script>
  var windowLoc = jQuery(location).attr('pathname'); 
  switch (windowLoc) {
    case '/the-old-url-I-want-to-change/':
      window.history.pushState(null, '', 'YOUR-MODIFIED-URL')
      break

    case '/another-old-url-I-want-to-change/':
      window.history.pushState(null, '', 'YOUR-MODIFIED-URL')
      break
  }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM