2016-04-24 80 views
1

我的應用程序包含一個非常簡單的登錄和兩個獨立的AJAX調用。我有一個正在加載的旋轉時自動隱藏每當頁面就緒時,它包含在index.js在Rails重定向後Javascript沒有執行

$(function() { 

    $("loading").hide(); 

    $("#scan_button").on("ajax:success", function(e, data, status, xhr) { 
     $("#standard_results").hide(); 
     $("#results").show(); 
     $("#results").html(data); 
    }); 

    $(document).ajaxStop(function() { 
     $("#loading").hide(); 
    }); 

    $(document).ajaxStart(function() { 
     $('#loading').show(); 
    }); 

}); 

當以下用戶登錄情況

class SessionController < ApplicationController 

    def create 
     user = User.find_by(username: params[:session][:username]) 

     if(user.password == params[:session][:password]) 
      log_in user 
      redirect_to root_path 
     end 
    end 

    def destroy 
     logout 
     redirect_to root_path 
    end 

end 

路由路徑把我帶回到index.js文件存在的'home#index'。當用戶登錄時發生重定向並且加載微調器被隱藏,並且所有JavaScript按預期執行。

當用戶點擊註銷但是發生重定向時,但顯示加載微調器並且沒有JavaScript被執行。這是我的index.html.erb文件,其中包含JavaScript。

<% content_for :title, "Network Monitor" %> 


<div class="container-fluid"> 

    <nav class="navbar narvbar-dark bg-inverse"> 
     <span class="navbar-brand">Network Monitor</span> 

     <%= link_to "Scan", scan_path, remote: true, class: "btn btn-secondary", id: "scan_button" %> 


     <% if logged_in? %> 

      <span class="pull-xs-right"><%= link_to "Logout", logout_path, class: "btn btn-secondary" %></span> 

     <% else %> 

      <%= form_for(:session, url: login_path, :html => {:class => 'form-inline pull-xs-right'}) do |f| %> 

       <%= f.text_field :username, class: 'form-control', placeholder: "Username" %> 
       <%= f.password_field :password, class: 'form-control', placeholder: "Password" %> 
       <%= f.submit "Log in", class: 'btn btn-primary', id: 'login_button' %> 

      <% end %> 
     <% end %> 
    </nav> 

    <div id="loading"> 
     <%= image_tag "loading.gif", class: "loading_gif" %> 
    </div> 

    <div class="row"> 
     <div class="col-md-12"> 
      <div id="scan_bar"> 
       <h3>Welcome to your network monitor!</h3> <br /> 

       <p>To get started hit the scan button in the top right corner, this will detect the computers that are alive on your network and show them below.</p> 
      </div> 
     </div> 
    </div> 

    <div class="row"> 
     <div id="results"> 
    </div> 

    <div id="standard_results"> 

    </div> 

回答

1

解決。這是因爲使用

$(document).on('turbolinks:load', function() {}); 

而不是我貼過那麼簡單,這似乎是導軌5和turbolinks希望您使用的方式,它的工作。

1

按照 turbolinks文件,我用的是事件page:change來解決這個問題:

$(document).on("page:change", function(){...}); 

這對我的作品。