简体   繁体   中英

AJAX: get page anchor with history.pushState

i made an ajax website so my dress page stay as index.php, so for get back my pages dress like www.example/about.html, i use history.pushState so it is working well, the dress changes when i click on a link button, my problem is that i can not use the refresh button or the back button of my browser, (my adress change but not the page).

this is my ajax page:

 $(document).ready(function(){ $("#menu a").click(function(){ var page=$(this).attr("href"); $.ajax({ url: "pages/"+page, cache:false, success:function(html){ afficher(html); history.pushState({key : 'value'}, 'hash', page); }, error:function(XMLHttpRequest,textStatus, errorThrown){ afficher("erreur lors du chagement de la page"); } }); return false; }); $('#container').on('click', '.vs-transform a', function(){ //Second ajax request page=$(this).attr("href"); $.ajax({ url: "pages/"+page, cache:false, success:function(html){ afficher(html); history.pushState({key : 'value'}, 'hash', page); }, error:function(XMLHttpRequest,textStatus, errorThrown){ afficher("erreur lors du chagement de la page"); } }); return false; }); window.onpopstate = function(event){ if(event.state === null){ alert('return'); } }; }); function afficher(data){ $("#container").fadeOut(500,function(){ $("#container").empty(); $("#container").append(data); $("#container").fadeIn(500); }); } 

history.pushstate is designed to add urls to the browser url history such that when you click the back or forward buttons, the saved page state and page content is restored.

When you click the refresh button, however, the browser simply reloads the saved url (ignoring the saved page in the history). If this was a fake url, you will get a 404 page not found error.

In essence, all urls pushed to the history should be valid urls which can be handled by the server (assuming you want to allow for refresh button presses).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM