JSON breaking back button in Chrome, Reload Button in IE (Showing as naked data)

会有一股神秘感。 提交于 2021-02-07 06:21:58

问题


Before Anything: $.getJSON back button showing JSON return data not the page did not help, as well as https://groups.google.com/group/angular/browse_thread/thread/3787ad609c0beb77/eb1b57069dab9f63 did not and the internet too did not help.

Here's the issue:

I'm calling an url from within a page to get json data, which then gets rendered with jquery templating inside this same page.

Imagine we're on the page http://someurl.com/search and we're starting a request like this

$.ajax({
  url: '/searchthis', //important, this is NOT THE SAME URL
  cache: false,
  type: 'GET',
  headers: {
    "Accept": "application/json",
  },
  dataType: 'json'
  success: function(data) {
    doSomethingWithResults(data);
  }
});

The Rack response has the cache control header set to no cache:

Cache-Control:no-cache

Everything works fine, but if you leave the page for another page in Chrome and then press the back button, you will get shown naked JSON Data. The same behaviour is there when you hit the reload Button in IE8. Both work perfectly fine if you just press Enter on the url in the adress bar.

I'm not getting how I could fix this, because the Chrome guys won't do it (see http://code.google.com/p/chromium/issues/detail?id=108425)

It seems to me like misinterpretation on the browsers side, because it caches something it really should not (response Header) and it caches something under a wrong url (because the JSON request does not hit the same URL)


回答1:


The problem was actually Rails: Both Chrome and IE request the last response with no specific format, so Rails just takes the first response block, which happened to be json in my case. Putting the html block in front of the json block solved the issue.

respond_to do |format|
  format.html { ... } //important because the request comes with no specific format
  format.json { ... }
end



回答2:


I had the same problem with Chrome. My controller's method does have the format.html

respond_to do |format|
  format.html
  format.js
end

It seems that Chrome caches results, so I was able to fix this by adding a data entry to my ajax request, like so:

$.ajax({
   url: '/restful/path',
   data: { format: 'js' }, // This line here
   dataType: 'json'
});

or you can pass the format by attaching it to the end of the request, just make sure you have the (.:format) option in your route

$.ajax({
   url: '/restful/path.js',
   dataType: 'json'
});

Hope this helps someone



来源:https://stackoverflow.com/questions/10715852/json-breaking-back-button-in-chrome-reload-button-in-ie-showing-as-naked-data

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