Javascript 基于AJAX的导航和浏览器恢复

Javascript 基于AJAX的导航和浏览器恢复,javascript,ruby-on-rails,ajax,browser-cache,Javascript,Ruby On Rails,Ajax,Browser Cache,我在Rails网站的一个部分中使用了基于AJAX的导航,使用了两个基本的jQuery挂钩,在这里用Coffescript表示: $(document).on 'click', 'a.ajax_nav', (e) -> window.history.pushState(null, "page title", this.href) $(window).on 'popstate', (e) -> $.getScript(document.location) 或等效的Javasc

我在Rails网站的一个部分中使用了基于AJAX的导航,使用了两个基本的jQuery挂钩,在这里用Coffescript表示:

$(document).on 'click', 'a.ajax_nav', (e) ->
  window.history.pushState(null, "page title", this.href)

$(window).on 'popstate', (e) ->
  $.getScript(document.location)
或等效的Javascript:

$(document).on('click', 'a.ajax_nav', function(e) {
  return window.history.pushState(null, "page title", this.href);
});
$(window).on('popstate', function(e) {
  return $.getScript(document.location);
});
导航工作正常,我可以使用浏览器的后退/前进按钮,并进行页面刷新,在这种情况下,操作将呈现相应的完整HTML视图,而不是执行JS脚本

但是,当我使用AJAX导航到页面时(因此通过执行脚本加载部分内容),关闭浏览器,然后重新打开它并选择“还原选项卡”选项,页面将显示脚本代码(但呈现ERB位),而不是执行它。我猜这是因为在请求时浏览器缓存的是服务器响应,这正是脚本

所以我的问题是,有没有一种方法可以操纵浏览器缓存来强制它重新加载页面,例如在呈现JS格式请求时将响应头设置为无缓存值?这是否会导致浏览器重新加载页面,从而返回HTML呈现(这将是非常好的)


谢谢大家!

通过将以下内容添加到我的根应用程序控制器(application_controller.rb)中解决了此问题:

class ApplicationController
这样,在整个应用程序的每个操作之前都会调用
set\u cache\u for_js
过滤器。如果请求的格式是javascript,则会对标题进行操作以“破坏”缓存,防止浏览器缓存javascript响应,从而强制基于URL重新加载页面,从而正确呈现文档

class ApplicationController < ActionController::Base
  .
  .
  before_filter :set_cache_for_js
  .
  .
  protected

    def set_cache_for_js
      set_cache_buster if request.format == 'text/javascript' # probably a better way to do this
    end

    def set_cache_buster
      response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
      response.headers["Pragma"] = "no-cache"
      response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
    end
.
.
end