在动作成功时调用javascript函数

时间:2017-05-23 19:19:06

标签: ruby-on-rails ruby-on-rails-4

我有一个名为USER_LOCATIONS的控制器。我想要的是,在动作成功后,创建页面重定向到另一个控制器,并且此时加载特定的javascript函数

这是因为我只需要在创建user_location时运行该函数,然后再进行

我该怎么做?

----------- ------------ EDIT USER_LOCATIONS

def create
            @user_location = UserLocation.new(user_location_params)

            respond_to do |format|
              if @user_location.save
                @resource_is_new = 'OK'  
                format.html { redirect_to root_path, notice: 'Ramal selecionado com sucesso.' }
                format.json { render :show, status: :created, location: @user_location }

              else
                format.html { render :new }
                format.json { render json: @user_location.errors, status: :unprocessable_entity }
              end
            end
        end

HOMECONTROLLER,INDEX VIEW

<% if @resource_is_new %>
  <%= content_for :extra_scripts do %>
    <script>
      alert('teste');
    </script>
  <% end %>
<% end %>

1 个答案:

答案 0 :(得分:0)

只有在加载特定视图时,您才可以使用extra_scripts内容块来调用Javascript函数。如果您只想在创建资源时重定向后运行此JS,那么您可以在控制器操作中设置一个实例变量来指定:

<% if @resource_is_new %>
  <%= content_for :extra_scripts do %>
    <script>
      // call your function here
    </script>
  <% end %>
<% end %>

将其放在重定向视图的底部,并确保在控制器操作成功时设置resource_is_new实例var。