后退按钮/退格键不能与window.history.pushState一起使用

Amn*_*tic 12 javascript jquery

我为我的网站制定了一个解决方案,其中包括使用ajax在网站上显示一般信息.在这样做时,每次用户使用window.history.pushState方法加载某些特定内容时,我都会更改URL.但是,当我按退格键或按回时,未加载旧URL的内容(但是加载了URL).

我已经尝试了几个解决方案,没有任何运气.

以下是其中一个ajax函数的示例:

$(document).ready(function(){
$(document).on("click",".priceDeckLink",function(){
    $("#hideGraphStuff").hide();
    $("#giantWrapper").show();
    $("#loadDeck").fadeIn("fast");
    var name = $(this).text();
    $.post("pages/getPriceDeckData.php",{data : name},function(data){
        var $response=$(data);
        var name = $response.filter('#titleDeck').text();
        var data = data.split("%%%%%%%");
        $("#deckInfo").html(data[0]);
        $("#textContainer").html(data[1]);
        $("#realTitleDeck").html(name);
        $("#loadDeck").hide();
        $("#hideGraphStuff").fadeIn("fast");
        loadGraph();
        window.history.pushState("Price Deck", "Price Deck", "?p=priceDeck&dN="+ name);
    });
});
Run Code Online (Sandbox Code Playgroud)

希望你们能帮忙:)

num*_*407 21

pushState单独使用后退/前进不会使您的页面功能.您需要做的是onpopstate自己收听和加载内容,类似于点击时发生的内容.

var load = function (name, skipPushState) {
  $("#hideGraphStuff").hide();
  // pre-load, etc ...

  $.post("pages/getPriceDeckData.php",{data : name}, function(data){
    // on-load, etc ...

    // we don't want to push the state on popstate (e.g. 'Back'), so `skipPushState`
    // can be passed to prevent it
    if (!skipPushState) {
      // build a state for this name
      var state = {name: name, page: 'Price Deck'};
      window.history.pushState(state, "Price Deck", "?p=priceDeck&dN="+ name);
    }
  });
}

$(document).on("click", ".priceDeckLink", function() {
  var name = $(this).text();
  load(name);
});

$(window).on("popstate", function () {
  // if the state is the page you expect, pull the name and load it.
  if (history.state && "Price Deck" === history.state.page) {
    load(history.state.name, true);
  }
});
Run Code Online (Sandbox Code Playgroud)

请注意,这history.state是历史API的一个不太受支持的部分.如果你想支持所有pushState浏览器,你必须有另一种方法来拉取popstate上的当前状态,可能是通过解析URL.

在这里缓存priceCheck的结果并将其从缓存中拉回/转发而不是发出更多的php请求,这将是微不足道的.

  • 我无法对此发表权威,但根据[mozilla的信息](https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history),window.history将其引入铬v5但国家财产没有出现直到v18.其他现代浏览器似乎从历史的引入中得到了支持. (2认同)

Sim*_*org 7

这对我有用。很简单。

 $(window).bind("popstate", function() {
    window.location = location.href
  });
Run Code Online (Sandbox Code Playgroud)