代码之家  ›  专栏  ›  技术社区  ›  Nikita Tonkoskur

使用Ajax时history.pushstate出现问题

  •  1
  • Nikita Tonkoskur  · 技术社区  · 7 年前

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

    问题是如果我继续 page3 从 page2 然后 第3页 如此反复,历史记录将包含所有这些转换,当我单击后退按钮时,我会不断地在 第二页 和 第3页 在我到达之前 page1 最终。我想要的是 page3 -> page2 -> page1 等等。

    你将如何解决这个问题?

    1 回复  |  直到 7 年前
        1
  •  1
  •   gearsdigital    7 年前

    这是未经测试的,但应该适合您的需要。这里的想法是更新 window.history 仅适用于新添加的URL。

    对于每个成功的请求,我们将检查当前URL是否存在于 myState . 如果没有,我们可以假设一个新页面,更新历史记录,并将URL放到我们的私有缓存中。 我的国家 .

    这将使您的URL保持有序,并防止重复的历史记录条目。

    请注意,此代码使用ES2015。您可以在Web上搜索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);
      }
    }