使用 AJAX 时 history.pushState 出现问题

Problem with history.pushState when using AJAX

我对 javascript 尤其是历史 API 很陌生。

我正在发出 AJAX GET 请求以加载网站上的下一页或上一页。

function ajax_get_update(url)
    {
    $.ajax({
        async: true,
        type: "GET",
        url: url,
        cache: true,
        success: function(result){
              sessionStorage.setItem("result", result);
              update_content(result);
            }
    });
    history.pushState(url, url, url)
}

AJAX 部分和更改页面内容工作得很好。如您所见,我正在使用 history.pushState(url, url, url) 将下一页添加到历史记录中,这样我就可以使用后退按钮返回到该页面。

url 看起来像这样 http://127.0.0.1:8000/?page=2

问题是如果我从 page2 继续 page3 然后再到 page3 等等,那么历史将包含所有这些转换,当我点击在后退按钮上,我一直在 page2page3 之间来回切换几次,然后才最终到达 page1。我要的是page3 -> page2 -> page1等等

你会如何解决这个问题?

这未经测试,但应该符合您的需要。这里的想法是仅针对新添加的 url 更新 window.history

对于每个成功的请求,我们都会检查当前 url 是否存在于 myState 中。如果不是,我们可以假定一个新页面并更新历史并将 url 放入我们的私有缓存 myState.

这将使您的 url 井井有条并防止重复的历史条目。

请注意,此代码使用的是 ES2015。您可以在网上搜索 polyfills :)

// it is probably not a good idea to keep your own history
let myState = [];

function ajax_get_update(url) {
  $.ajax({
    async: true,
    type: "GET",
    url: url,
    cache: true,
    success: function(result) {
      sessionStorage.setItem("result", result);
      update_content(result);
      update_history(url);
    }
  });
}

function update_history(url) {
  // window.history is only updated when the current url is not
  // saved in our private history
  if (!myState.includes(url)) {
    history.pushState(url, url, url);
    myState.push(url);
  }
}