admin管理员组

文章数量:1336659

I'm generating a chart in Rails using a d3.js JSON callback like this:

View

d3.json(document.URL, function(data){ 
    // generate chart
}

Controller

def index
    respond_to do |format|
        format.html do
            # return the HTML
        end
        format.json do
            # return the JSON
        end
    end
end

All works fine. However when a user leaves this chart, and then navigates back to it using the "back" button on their brower they are presented with the JSON rather than the HTML.

Can you suggest how I might fix this?

I'm generating a chart in Rails using a d3.js JSON callback like this:

View

d3.json(document.URL, function(data){ 
    // generate chart
}

Controller

def index
    respond_to do |format|
        format.html do
            # return the HTML
        end
        format.json do
            # return the JSON
        end
    end
end

All works fine. However when a user leaves this chart, and then navigates back to it using the "back" button on their brower they are presented with the JSON rather than the HTML.

Can you suggest how I might fix this?

Share Improve this question edited Sep 12, 2012 at 13:04 paxRoman 2,0623 gold badges19 silver badges32 bronze badges asked Aug 15, 2012 at 9:15 Derek HillDerek Hill 6,4645 gold badges58 silver badges79 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

Well, this is because when you hit back button the browser is serving last cached content for the given URL. IIn your case the last content is JSON requested by AJAX (D3).

In addition to accepted answer you can also try the other way - just append .html to page URL. You can automate it by adding this filter to controller or ApplicationController:

   before_filter do
     if request.format == :html && !params[:format]
       redirect_to format: :html
     end
   end

There is also a third standard way with Vary: Accept header but it may cause some troubles because of this Chrome bug and some problems described in The browser cache is Vary broken

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

As inspired by this question.

本文标签: