[英]How to refresh the browser with JS after clicking a link_to tag in a Rails app
I'm trying to refresh the browser after the user clicks a link to an action that updates the database. 用户单击更新操作的链接后,我试图刷新浏览器。
I want to avoid using redirect_back to prevent being sent back to the top of the screen after reload so I'm adding a JS click listener to the link_to tag with a code like this: 我想避免使用redirect_back来防止重新加载后发送回屏幕顶部,因此我将JS Click侦听器添加到link_to标记中,其代码如下:
# in my view
<h5 class='my-link'><%= link_to 'vote', vote_path' %></h5>
# at the bottom of my application layout
<script>
$('.my-link').click(function (event) {
window.location.reload(true);
});
</script>
The JS code listener works OK in that if I click on any section of the h5 element the page will reload. JS代码侦听器工作正常,因为如果我单击h5元素的任何部分,页面将重新加载。 However, when I click in the link the application will go to the relevant controller#action but the page wont reload.
但是,当我单击链接时,该应用程序将转到相关的controller#action,但该页面不会重新加载。
I'm assuming I'm missing a way to execute first the link action and then force the refresh. 我假设我缺少一种方法,该方法首先执行链接操作,然后强制刷新。 So at click the app records a vote and then JS force a reload.
因此,在单击时,该应用程序记录了投票,然后JS强制重新加载。 Can you see any way I can achieve this?
您能看到我能做到的任何方式吗? Thanks.
谢谢。
UPDATE UPDATE
I some what solved this issue by adding a timer to the JS event so it gives time for the link to reach the controller and do the action and do the reload after it. 我通过在JS事件中添加计时器解决了这个问题,从而为链接提供了到达控制器的时间,并可以在链接完成之后进行操作和重新加载。
<script>
$(document).ready(function() {
$('.puke-icon, .clean-link, .comment-send').click(function() {
setTimeout(function(){
window.location.reload(true); },
50);
});
});
</script>
This is probably too hacky so hopefully you can provide more elegant approaches thanks! 这可能太hacky了,希望您可以提供更优雅的方法,谢谢!
In your vote controller action
, use location.reload()
in respond_to do format
. 在您的
vote controller action
,使用respond_to do format
location.reload()
。
respond_to do |format|
format.js {render inline: "location.reload();" }
end
View: 视图:
<h5 class='my-link'><%= link_to 'vote', vote_path' %></h5>
Controller: 控制器:
class VotesController < ApplicationController
def vote
----------------------
// your code goes here
----------------------
respond_to do |format|
format.js {render inline: "location.reload();" }
end
end
end
This will reload the page after the database action is completed. 数据库操作完成后,将重新加载页面。
$('.product').click(function () { location.reload(); })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> <div class="container"> <div class="row" id="footerRow"> <div class="col-xs-12 product"> <h2>Product</h2> <div> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.