首页 > 解决方案 > 以设定的时间间隔刷新 DIV 元素

问题描述

对于 Django 项目中的聊天应用程序,我使用登录用户的链接填充侧边栏。这些链接会打开一个聊天弹出窗口(类似于 FB stlye)。如果我刷新页面,任何打开的弹出窗口都会关闭。我只想刷新侧边栏以反映用户是否已注销。此代码刷新整个页面并关闭所有打开的弹出窗口。

$(function(){
    $('#sidebar-name').on('scroll', function(){
        scrolling = true;
    });
    setTimeout(function() { location.reload() },3500);

});

我使用下面的代码来获取消息并刷新消息框

function getMessages(){
    if (!scrolling) {
        $.get('/chatpop/messages/', function(messages){
            console.log(messages);
            $('#msg-list').html(messages);
            var chatlist = document.getElementById('msg-list-div');
            chatlist.scrollTop = chatlist.scrollHeight;
        });
    }
    var scrolling = false;
}

$(function(){
    $('#msg-list-div').on('scroll', function(){
        scrolling = true;
    });
    refreshTimer = setInterval(getMessages, 10000);
});

我也尝试了以下但没有工作..

$(function(){
    $('#sidebar-name').on('scroll', function(){
        scrolling = true;
    });
    (function() { load(location.href +'#sidebar-name') },10000);

});

我只需要以不关闭已打开的聊天弹出窗口的方式刷新侧边栏。

正在使用的 HTML 是..

 <div class="chat-sidebar">
        <div class="sidebar-name">
            <!-- Pass username and display name to register popup -->
            {% for user in request.online_now %}
                {% if request.user != user %}
            <a href="javascript:register_popup('{{ user }}', '{{ user }}');">
            {% for img in users %}
                {% if img == user %}
        {% thumbnail img.profile.photo "30x30" crop="100%" as im %}
         <img src="{{ im.url }}" class="user-detail">
            {% endthumbnail %}{% endif %}{% endfor %}
            <span>{{ user }}</span>
            </a>{% endif %}{% endfor %}

看过一些stackoverflow的答案。但他们似乎都在发生事件时处理重新加载。我只是想以设定的时间间隔刷新。很多thks ..

标签: javascriptjqueryhtmldjango

解决方案


创建一个以 html 形式返回在线用户的视图,并每隔一段时间加载该 url。

setInterval(function() {
      $("#sidebar-name").load("{% url 'get_active_users' %}"); // you need to create get_active_users view
}, 5000);

推荐阅读