pushState和back按钮有效,但内容不会改变

Dal*_*raz 8 html javascript jquery html5

它确实加载了一个新页面并且网址确实更新了,但是当我按下后退按钮时,只有网址已更改而没有刷新但内容却没有.

$('button').click(function(){
  window.history.pushState({}, '', 'page2.php');
  $('body').html('<div class="loading.gif"></div>');

  //Load Page
  $.get('page2.php', function(data){
    $('body').html(data);
  };

  //Edited 
  $(window).bind('popstate', function(){
    //What should I code here??
  });
});
Run Code Online (Sandbox Code Playgroud)

ano*_*ode 8

我做了类似的事情:

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

它工作得很好.
代码从网址获取位置并重定向到此网址.

  • 这是整页重新加载.它不是History API的用途. (4认同)

小智 5

我用它来更改栏地址并保存当前状态,包括当前的 html 正文,并且我在返回按钮单击时重新加载它,而无需任何其他 ajax 调用。全部保存在您的浏览器中:

  1. $(document).ajaxComplete(function(ev, jqXHR, settings) {
    
        var stateObj = { url: settings.url, innerhtml: document.body.innerHTML };
        window.history.pushState(stateObj, settings.url, settings.url);
    });
    
    
    window.onpopstate = function (event) {
        var currentState = history.state;
        document.body.innerHTML = currentState.innerhtml;
    };
    
    Run Code Online (Sandbox Code Playgroud)


Joh*_*ing 1

您需要实现 popstate 事件。当您按下状态后单击后退按钮时,页面会收到 popstate 事件。您需要在其中将页面内容替换为正确的页面。

请参阅MDN 中的示例

更新的代码:

$('button').click(function(){
  // Store some information in the state being pushed
  window.history.pushState({url:'page2.php'}, '', 'page2.php');
  $('body').html('<div class="loading.gif"></div>');

  //Load Page
  $.get('page2.php', function(data){
    $('body').html(data);
  };

  //Edited 
  $(window).bind('popstate', function(event){
    var url = null;

    if (event.state && event.state.url) {
        url = event.state.url;
    } else {
        url = 'index.html'; // or whatever your initial url was
    }

    // Update the contents of the page with whatever url was stored in the state.
    $.get(url, function(data){
        $('body').html(data);
    };
  });
});
Run Code Online (Sandbox Code Playgroud)