简体   繁体   English

AJAX:使用history.pushState获取页面锚点

[英]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). 我建立了一个ajax网站,因此我的着装页面保持为index.php,因此要获取我的页面着装,如www.example / about.html,我使用history.pushState使其运作良好,当我单击链接按钮,我的问题是我不能使用浏览器的刷新按钮或后退按钮(我的地址更改,但页面不可用)。

this is my ajax page: 这是我的ajax页面:

 $(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. history.pushstate旨在将URL添加到浏览器的URL历史记录中,这样,当您单击后退前进按钮时,将恢复已保存的页面状态和页面内容。

When you click the refresh button, however, the browser simply reloads the saved url (ignoring the saved page in the history). 但是,当您单击刷新按钮时,浏览器仅重新加载保存的URL(忽略历史记录中的保存页面)。 If this was a fake url, you will get a 404 page not found error. 如果这是一个伪造的URL,您将收到404页面未找到错误。

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). 从本质上讲,推送到历史记录的所有URL应该是服务器可以处理的有效URL(假设您希望允许按下刷新按钮)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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