【问题标题】:How do I change the URL without reloading the page?如何在不重新加载页面的情况下更改 URL?
【发布时间】:2020-12-29 12:56:32
【问题描述】:

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

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

然后我根据this answer 组合了一个用于更改 URL 的 sn-p。但这就是我卡住的地方。

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

【问题讨论】:

    标签: javascript ajax url


    【解决方案1】:

    如果您真正想要做的只是更改 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>
    

    【讨论】:

      猜你喜欢
      • 2020-04-20
      • 2020-10-04
      • 2011-11-27
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 2016-10-28
      相关资源
      最近更新 更多