HTML5历史记录API:在“返回”时显示JSON到另一页,然后“转发”再次 [英] HTML5 History API: JSON displayed when going "back" to another page, and then "forward" again

查看:149
本文介绍了HTML5历史记录API:在“返回”时显示JSON到另一页,然后“转发”再次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,其中有几个搜索/过滤按钮,点击后,通过AJAX刷新下面列表的内容。



在这个过程中,我修改历史记录(通过pushstate),以便新过滤的页面可以加入书签,因此后退按钮可以正常工作。我也在听popstate事件,对Back做出反应。



我的代码看起来或多或少像这样:

  window.addEventListener(popstate,function(ev){
if(!window.history_ready){return;} //避免一次运行加载
refreshFilter(window.location.href,true);
});
$ b $ refreshFilter:function(newURL,backButtonPressed){
$ .ajax({url:newURL})。done(blah);

if(!backButtonPressed){
window.history_ready = true;
history.pushState(null,null,newURL);




$ b $ p
$ b

奇妙的是,除了一个奇怪的情况。 。


  • 用户在页面A中

  • 他们点击链接转到此页面(我们称之为B)

  • 他们运行几个过滤器,然后按Back几次,这样他们又回到了初始状态B

  • 他们再次点击返回,这会将他们发送回A。

  • 此时,如果他们按Forward,而不是发出请求再次向服务器发送页面B时,浏览器只显示一堆JSON代码作为页面内容(这个JSOn是我的AJAX请求中的一个过滤东西的响应)



至少在最新的Chrome中



为什么会发生这种情况,我该如何避免它?

解决方案

Chrome会缓存您访问的页面,当您返回或转发时,它会使用缓存快速显示页面。如果您用于通过AJAX从服务器检索JSON的URL与Chrome相同,那么Chrome可能会从缓存中选择该页面,而不是良好的HTML,它只是JSON转储。


I have a page where there are several search / filter button which, when clicked, refresh the contents of a list below through AJAX.

In the process, I'm modifying history (through pushstate) so that the new filtered page is bookmarkable, and so the back button works. I'm also listening for the popstate event, to react to Back.

My code looks more or less like this:

window.addEventListener("popstate", function(ev) {
  if (!window.history_ready) { return; } // Avoid the one time it runs on load 
  refreshFilter(window.location.href, true);
});

refreshFilter: function(newURL, backButtonPressed){
  $.ajax({ url: newURL}).done( blah );

  if (!backButtonPressed) {
    window.history_ready = true;
    history.pushState(null, null, newURL);
  }
}

This works wonderfully, except for one weird case...

  • User is in page "A"
  • They click a link to go to this page that plays with history (let's call it "B")
  • They run a couple of filters, then press Back a few times, so they're back at the initial state of "B"
  • They click Back once again, which sends them back to "A"
  • At this time, if they press Forward, instead of making a request to the server again for Page "B", the browser simply displays a bunch of JSON code as the page contents (this JSOn is the response of one of my AJAX requests to filter stuff)

At least in latest Chrome

Why is this happening and how can I avoid it?

解决方案

Chrome caches the pages you visit and when you go back or forward it uses the cache to display the page quickly. If the URLs you are using to retrieve JSON from the server by AJAX is the same one Chrome would hit, then it's possible Chrome is picking that page from the cache, which instead of being the nice HTML it's just a JSON dump.

这篇关于HTML5历史记录API:在“返回”时显示JSON到另一页,然后“转发”再次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆