如何根据控制器中的某些条件运行javascript代码?例如,当存在alert
时,我想显示JavaScript params[:alert]
。我该怎么办?
答案 0 :(得分:4)
在您的视图文件中
<% if params[:alert] %>
<script>alert("Hello");</script>
<% end %>
答案 1 :(得分:0)
您始终可以在控制器中进行操作
def some_action
if condition
@run_javascript = true
else
@run_javascript = false
end
end
然后在您看来
<script type="text/javascript">
<% if @run_javascript %>
alert('Something was wrong');
<% end %>
</script>
答案 2 :(得分:0)
#view page
<script>
<% flash.each do |k,v| %>
<% if k == "success" %>
success("<%= v %>");
<% else %>
alert("<%= v %>")
<% end %>
<% end %>
</script>
您只需要flash:{ alert: or success:}
#controller
respond_to do |format|
format.html{ redirect_back(fallback_location: '/orders', flash: { alert: "custom message" } ) }
end