javascript - 以设定的时间间隔刷新 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 ..
解决方案
创建一个以 html 形式返回在线用户的视图,并每隔一段时间加载该 url。
setInterval(function() {
$("#sidebar-name").load("{% url 'get_active_users' %}"); // you need to create get_active_users view
}, 5000);
推荐阅读
- docker - 我收到一个错误,我无法连接到 macos :: daemon daemon
- node.js - 我可以模拟导入到我用 jest 导入的模块中的单个函数吗?
- android - 选择选项时按钮破坏应用程序
- python - Python Click:如何实现类似于`--help`的帮助命令?
- spring-mvc - InternalResourceViewResolver 和 UrlBasedViewResolver 之间的确切区别是什么
- c# - 未管理的内存结构
- node.js - 错误:中间件中的 passport.initialize() 未使用
- r - 如何从总和为 1 的指数分布生成随机数(概率)
- python - 为什么我的 DNA 模式 Python 代码没有给出正确的输出?
- php - 跳过使用 PHP 将 csv 上传到 mysql 的第一行