2012-12-25 31 views
0

我已經實現自動重新計數未讀的數量。
它每15秒回傳未讀消息的數量。
但即使用戶未登錄,也會發生同樣的情況。如何僅在登錄時運行setInterval ajax調用?

如何阻止此問題?我想這樣做,只有當用戶已登錄。

我有一個像爵士這樣

jQuery(document).ready(function() { 
    refreshPartial(); 
    setInterval(refreshingPartial, 15000) 
}); 


function refreshingPartial() { 
    $.ajax({ 
    url: "/messages/refreshing_partial", 
    type: "GET", 
    dataType: "script", 
    }); 
} 

回答

2

使用內聯JS

<% if current_user %> 
    <%= javascript_tag do %> 
     jQuery(document).ready(function() { 
      refreshPartial(); 
      setInterval(refreshingPartial, 15000) 
     }); 


     function refreshingPartial() { 
      $.ajax({ 
      url: "/messages/refreshing_partial", 
      type: "GET", 
      dataType: "script", 
      }); 
     } 
    <% end %> 
<% end %> 

OR

類添加到身體,如果用戶登錄並控制課程。

<body class="<%= "logged-in" if current_user %>"> 

</body> 

,改變你的JS有點

jQuery(document).ready(function() { 
    if ($("body").is(".signed-in")) { 
    refreshPartial(); 
    setInterval(refreshingPartial, 15000) 
    }; 
}); 
+0

這看起來很完美。謝謝! – HUSTEN

0

只有當用戶在簽署的refreshPartial js腳本應該呈現以下應該做的伎倆:

<script type="text/javascript"> 
    $(document).ready(function() { 
     <% if is_user_signed_in %> 
      refreshPartial(); 
      setInterval(refreshingPartial, 15000); 

      function refreshingPartial() { 
       $.ajax({ 
         url: "/messages/refreshing_partial", 
         type: "GET", 
         dataType: "script", 
       }); 
      } 
     <% end %> 
    }); 
</script> 
+0

您無法直接在js中檢查會話變量。 Js已經預編譯。 – emrahbasman

+0

不,這不會起作用 – HUSTEN

+0

您是否注意到了封閉的腳本標記?在.erb文件中,這應該是完美的。只有在文檔被渲染後,腳本纔會被編譯。 refreshPartial()方法僅在用戶登錄時執行。讓我知道您面臨的問題。 – atmaish

相關問題