The pushState and back button works, but the content does not change

It loads a new page and the URL is updated, but when I click the back button, only the URL has changed without updating, but the content does not.

$('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?? }); }); 
+6
source share
3 answers

I did something like this:

  $(window).bind('popstate', function(){ window.location.href = window.location.href; }); 

And it works great. The code takes the location from the URL and redirects to that URL.

+7
source

I use this to change the address of a string and save the current state, including the current html body, and reload it on the back bot click without any other ajax call. Everything is saved in your browser:

  •  $(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; }; 
+2
source

You need to implement the popstate event. When you click the back button after the state is clicked, the page receives a popstate event. In it you need to replace the contents of the page with the correct page.

See an example from MDN

Updated code:

 $('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); }; }); }); 
0
source

Source: https://habr.com/ru/post/973191/


All Articles