简体   繁体   中英

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. 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.

An alternative would be to create a view to create.js.erb , and it run JS:

Your controller:

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

create.js.erb

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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