简体   繁体   中英

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. I also need the forward and back browser buttons to go to the original URL, not the new URL.

I created a switch to determine if I am on one of the pages which needs to change the URL.

And then I put together a snippet for changing the URL based on this this answer . 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. Also what should I be passing in for 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. The only part of this whole business that you need is the 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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