Moving back to a pushState entry that used ajax

喜你入骨 提交于 2019-12-03 05:06:58

问题


I'm having an issue with the following situation.

  1. User visits site
  2. User clicks link which uses history.pushState to update the url
  3. Partial page content loaded via ajax (using jQuery)
  4. User clicks regular link which loads a new page
  5. User clicks back to return to the pushState entry
  6. The page now displays only the page partial that was retrieved via ajax

I've souped up a site using pushState for various things and the result is a shockingly responsive web app, but this issue is preventing me from using this.

Here's a sample of the code:

$('a').live('click', function(){
  history.pushState({}, '', this.href);
  popstate(this.href);
  return false;
});

popstate = function(url){
  $('#content').load(url);
}
window.onpopstate = function(event){
  popstate(window.location.href);
  event.preventDefault();
}

Notes:

  • When placing an alert in the window.onpopstate function it appears that the event is NOT triggered at step 5. Is this a bug?
  • The issue only occurs when ajax is used.
  • I have had to separate the popstate function so I can call it after pushState. Is there a way to manually trigger the window.onpopstate event?

回答1:


It seems that some browsers often confuse the partial loaded via ajax and the entire page, decorated with its layout. That's because they both have the same URL. So when the user click on the back button, the browser won't load the URL and will just display the partial it has previously downloaded via ajax.

To avoid this and maintain two separate internal caches (one for the partial page and one for the entire page), you should add a GET parameter in the URL when calling via ajax. Like this in your code:

popstate = function(url){
  $('#content').load(url+'?_ajax=1');
}

Hope this helps.



来源:https://stackoverflow.com/questions/6309477/moving-back-to-a-pushstate-entry-that-used-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!