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

时间:2020-09-11 01:33:03

标签: javascript ajax url

在两个不同的页面上,我试图更改URL而无需重新加载页面。我还需要前进和后退浏览器按钮以转到原始URL,而不是新URL。

我创建了一个开关来确定我是否在需要更改URL的页面之一上。

然后,我根据此this answer整理了一个用于更改URL的代码段。但这就是我被困住的地方。

因为我不确定应该如何调用processAjaxData,我以为这是我传入新URL标记的地方。另外,我应该为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>

1 个答案:

答案 0 :(得分:0)

如果您实际要做的只是更改URL,并且您不介意在用户单击“后退”按钮时重新加载页面,则可以删除大部分示例代码。您需要整个业务的唯一部分是pushstate。因此,只需将其拔出并将其直接放在交换机中即可。像这样:

<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>