简体   繁体   English

在控制器中重定向后如何执行JS(Rails)?

[英]How to execute JS after redirect in a controller (Rails)?

Create 创造

if @image.save
    format.html { redirect_to vote_path(@image) }
    format.js { render :js => "my_function();" }
end

so I'd like to fire up a function after the redirect has happened, but this doesn't work. 因此,我想在重定向发生后启动一个函数,但这不起作用。 Are there any other methods I could try and could you suggest me any please? 我还有其他方法可以尝试吗,您能建议我吗?

Thank you. 谢谢。

The redirect and render are separate. 重定向和渲染是分开的。 If you want it to run JS after the redirect, you can put some in the view that the vote_path is using. 如果您希望它在重定向后运行JS,则可以将某些视图放置在vote_path正在使用的视图中。 If you only want it to run after the redirect and not on the page load, you can set a flash before you redirect, and then check for the flash in the view. 如果只希望它在重定向后运行,而不是在页面加载时运行,则可以在重定向之前设置Flash,然后在视图中检查Flash。

An alternative would be to create a view to create.js.erb , and it run JS: 一种替代方法是创建一个视图create.js.erb ,并运行JS:

Your controller: 您的控制器:

if @image.save
  format.html { redirect_to vote_path(@image) }
  format.js { }
end

create.js.erb create.js.erb

$("#share_window").show();

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

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