简体   繁体   English

仅当用户登录时才运行 JavaScript 函数 - Django

[英]Run JavaScript function only if user logged in - Django

So I have a function that checks a user's mailbox and a variable defined after it that sets the frequency of this function.所以我有一个函数来检查用户的邮箱和一个在它之后定义的变量来设置这个函数的频率。 However, I don't want the function to send unnecessary requests if the user isn't even signed in to the website.但是,如果用户甚至没有登录网站,我不希望该功能发送不必要的请求。 Where/how would I pass the if user.is_authenticated parameter to this code to check?我在哪里/如何将 if user.is_authenticated 参数传递给此代码以进行检查?

function checkMail() { // Checks for new mail in user's inbox
$.ajax({
   url: "/checkMail/",
   type: "POST",
   success: function(data) {
            obj = JSON.parse(data);
            if(!obj.read){
                    $('#mailsquare').css('background-color', '#A80000');
                    $('.dropdown-menu').prepend('<li class="message" id="{{item.id}}">'+obj.newest.substring(0,30)+'</li>');
            } else {
                    $('#mailsquare').css('background-color', '#1b1b1b');
            }
   },
   error: function(xhr, status, error) { console.log(xhr.status); console.log(xhr.responseText); console.log(status); console.log(error); }
   });
}
var interval = setInterval(checkMail, 10000);  // Set interval for frequency of mail checks

In your actual Django template, you can have a JavaScript block wrapped in a template tag that checks the user is logged in.在您的实际 Django 模板中,您可以将 JavaScript 块包装在模板标记中,用于检查用户是否已登录。

{% if user.is_authenticated %}
    <script type="text/javascript">
         setInterval(checkMail, 10000);
     </script>
{% endif %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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