简体   繁体   English

使用浏览器历史记录时,Rails link_to remote true问题

[英]Rails link_to remote true issue when with browser history

I'm using the following code to get data via JS request on my search page 我正在使用以下代码通过我的搜索页面上的JS请求获取数据

<%= link_to 'All', '/search?type=all', id: 'active', remote: true %>
<%= link_to 'Photographers', '/search?type=photographers', remote: true %>

It's all working fine and I'm getting data as expected. 一切正常,我正在按预期获得数据。 But when I click some other link and then hit back button (provided by browser) it's showing me the JS request data on a blank page instead of going back to search page. 但是当我点击其他链接然后点击后退按钮(由浏览器提供)时,它会在空白页面上显示JS请求数据,而不是返回搜索页面。

Is there any workaround or fix to this? 有没有解决方法或修复此问题?

in routes.rb 在routes.rb中

resources :search, only: [:index]

in search controller 在搜索控制器中

def index
  // search processing

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

search/index.js.erb 搜索/ index.js.erb的

$('#search-area').html("<%= j render partial: 'search_area' %>");

I'm using Rails 5.0 with Puma 我正在使用与Puma的Rails 5.0

As I thought. 和我想象的一样。 The back button goes to the last request which is the JS file. 后退按钮转到最后一个请求,即JS文件。 ALL it does is render a partial but since it doesn't have a base template to go from all you get is the search data from the partial. 它所做的全部是渲染部分,但由于它没有基本模板,所以你得到的是来自部分的搜索数据。

The way I have gotten AJAX partials to work so far is to have a div tag (or anything with an ID really) in the .html.erb file. 到目前为止,我已经让AJAX部分工作的方法是在.html.erb文件中有一个div标签(或任何具有ID的东西)。 For instance from a project with a AJAX sortable table: 例如,来自具有AJAX可排序表的项目:

index.html.erb

...
<div class="card card-block" id="article-index">
    <%= render 'indextable' %>
</div>
...

index.js.erb

$("#article-index").html("<%= escape_javascript(render("indextable")) %>");

Both refernce a partial for the table data I want to render. 两者都引用我要渲染的表数据的部分。 The trick is here in the .js.erb file to use the syntax of setting the innerHTML to a rails escape_javascript(render..) call. 诀窍是在.js.erb文件中使用将innerHTML设置为rails escape_javascript(render..)调用的语法。 That way back navigation will work from another page back to the search result page. 这样,返回导航将从另一个页面返回到搜索结果页面。

Give that a try and let me know if it did the trick. 尝试一下,让我知道它是否成功。 Odds are you will get the HTML template for the search result page rendered but without any data. 可能的情况是,您将获得呈现的搜索结果页面的HTML模板,但没有任何数据。 AJAX generally won't work with the browser back button. AJAX通常不能与浏览器后退按钮一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM