通过js设置页面历史记录和页面内容

Set page history with page content by js

本文关键字:记录 历史 js 通过 设置      更新时间:2023-09-26

我使用了pace.js,但pace的问题是,加载动画是在页面完全加载后显示的。

因此,我尝试并制定了一个解决方案,点击页面上的每个链接,jquery从浏览器中获取并停止直接指向该链接的事件,并向该链接发送ajax get请求。加载页面时,会在当前页面上显示动画。页面完全加载后,它会用接收到的数据替换整个当前文档,并替换地址栏中的页面url。

    <script type="text/javascript">
    $( document ).ready(function() {
     $('a').click(function() {
            var dt;
            if (/#/.test(this.href)) {
                return true;
            }else{
                document.getElementById("before-loader").style.display= "block";//show loading animation
            var that = this;
            $.ajax({
                  type: "GET",
                  url: that.href,
                  success: function(response){
                    document.open();
                    document.write(response);
                    document.title = response.pageTitle;
                    window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", that.href);
                document.close();
                  },
                  error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus + ' ' + errorThrown);
                    document.getElementById("before-loader").style.display= "none";//hide loading animation
                  }
                });
            return false;
          }
      });
    });
    </script>

问题是点击浏览器返回按钮,地址栏中的url正在更改,但页面内容仍然保持不变。我该如何克服这个问题?

更新

se0kjun的答案并没有解决我的问题(我希望它能在复制/粘贴提供的代码后工作),但让我朝着正确的方向前进。经过一些研究和改写流程,它是有效的,但我仍然困惑它为什么有效。

$( document ).ready(function() {
 $('a').click(function() {
        if (/#/.test(this.href)) {
            return true;
        }else{
      window.history.pushState(null, 'Production Workflow & Sales Management', this.href);
            loadContent(this.href);
        return false;
      }
  });
});

function loadContent(href) {
  document.getElementById("before-loader").style.display= "block";
  $.ajax({
    type: "GET",
    url: href,
    success: function(response){
      document.open();
      document.title = response.pageTitle;
      document.write(response);
      document.close();
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      alert(textStatus + ' ' + errorThrown);
      document.getElementById("before-loader").style.display= "none";
    }
  });
}

window.onpopstate =  function(event) {
  link = location.pathname.replace(/^.*[''/]/, ""); // get filename only
  loadContent(link);
};

也许我应该多学习。

我想您想要popstate事件。

当您单击链接时,ajax请求that.href。之后,如果请求成功,您将得到响应并调用pushstate

单击后退按钮时,会触发popstate事件。您可以在popstate事件处理程序中加载上一页。

以下是popstate 的使用示例

window.onpopstate =  function(event) {
  //you add a path in pushstate
  $('.container').load(event.state.path);
  alert('popstate');
};

这是一个小提琴