点击浏览器"后退"按钮显示JSON而不是HTML(使用Rails&d3.js)

Der*_*ill 6 javascript charts json ruby-on-rails d3.js

我正在使用像这样的d3.js JSON回调在Rails中生成一个图表:

视图

d3.json(document.URL, function(data){ 
    // generate chart
}
Run Code Online (Sandbox Code Playgroud)

调节器

def index
    respond_to do |format|
        format.html do
            # return the HTML
        end
        format.json do
            # return the JSON
        end
    end
end
Run Code Online (Sandbox Code Playgroud)

一切正常.但是,当用户离开此图表,然后使用其浏览器上的"后退"按钮导航回到它时,它们将显示JSON而不是HTML.

你能建议我怎么解决这个问题吗?

ger*_*tas 5

好吧,这是因为当您点击后退按钮时,浏览器正在为给定的URL提供最后缓存的内容.在您的情况下,最后一个内容是AJAX(D3)请求的JSON.

除了接受的答案,您还可以尝试其他方式 - 只需附加.html到页面URL.您可以通过将此过滤器添加到控制器或自动执行此操作ApplicationController:

   before_filter do
     if request.format == :html && !params[:format]
       redirect_to format: :html
     end
   end
Run Code Online (Sandbox Code Playgroud)

还有第三种带Vary: Accept标题的标准方法,但由于这个Chrome错误可能会导致一些问题,并且浏览器缓存中描述的一些问题是Vary破坏


Der*_*ill 2

d3.json(window.location.pathname + ".json" + window.location.search.substring(0), function(json){  
    // generate chart
}
Run Code Online (Sandbox Code Playgroud)

正如受到这个问题的启发。