每秒刷新一次新消息

时间:2017-05-07 21:10:13

标签: javascript python html django

在我的Django网站中,我有一个范围,显示用户在下图中喜欢的新消息数量:
enter image description here
现在我可以在每个django视图中刷新这个值,这是我base.html的一部分

Views.py

def someView(request,pk):
...
    mcount = UserMessage.objects.filter(receiver = request.user.pk, isRed = 0).count()
...
    return render(request, 'app/somehtml.html', {...'mcount':mcount...})

base.html文件

...
  <span class="messageCount"aria-hidden="true"> {{ mcount }} </span>
...

我想要做的是每隔几秒刷新一次,而无需用户重新加载页面。 我怎么能实现这个目标?

2 个答案:

答案 0 :(得分:0)

您必须使用Javascript在客户端进行自动刷新。

window.setTimeout(function () {
    location.href = "http://yourwebsite.com";
}, 30000);

每30秒刷新一次页面。

还有meta html标签:

<head>
  <meta http-equiv="refresh" content="30">
</head>

这也会每30秒刷新一次页面。

答案 1 :(得分:0)

这样的事情:

function autoReloadSpan(){
    $.ajax({ url: "/poll/",
                     data: {},
                     type: 'GET',
                     success: function(data) {
                         $('.messageCount').html(data);
                     },
    });
}

autoReloadSpan(); // This will run on page load
setInterval(function(){
    autoReloadSpan() // this will run after every 5 seconds
}, 5000);
相关问题