jquery - 在django中用jquery实时更新模板可以吗?
问题描述
我有一个脚本,在我的 django 模板中每 2 秒发出一个 ajax 请求。该脚本基本上每 2 秒调用一次cpu_view
函数views.py
,该函数更新填充我的 django 表所需的数据。
一切正常,除了页面或特别是页面的 html 内容每次都会刷新,包括使页面看起来有点奇怪的 IMO 的所有按钮。所以我想也许有更好的方法来做到这一点。基本上,我在这里要做的是为我的服务器创建一个小型监控应用程序。
任何建议或帮助表示赞赏。
模板cpu.html
{# server/templates/server/table.html #}
{% load render_table from django_tables2 %}
{% load static %}
<!doctype html>
<html>
<head>
<title>List of persons</title>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript" src="{% static '/server/jquery-3.4.1.js' %}"></script>
<script type="text/javascript">
function executeQuery() {
$.ajax({
type: 'GET',
url: '/server/cpu',
success: function(data) {
$("html").html(data)
}
});
}
setInterval(executeQuery, 2000);
</script>
</head>
<body>
{% render_table table %}
</body>
</html>
视图.py
def cpu_view(request):
output = []
listServers = Serveurs.objects.all()
for x in get_proc_output():
pid = x.get('pid')
for y in get_netstat_output():
if pid in y.values():
output.append({**x,**y})
for i in listServers:
for j in output:
if i.port in j.values():
j['type_server'] = i.type_du_serveur
table = TableServeur(output)
RequestConfig(request).configure(table)
return render(request, 'server/table.html', {'table': table})
解决方案
推荐阅读
- html - 如何防止我网站中的视频在 ipad 上以 PIP 模式播放?
- c++ - 是否可以 dllexport 已通过 using-declaration 访问的方法?
- java - 如何验证是否显示 toast 消息?
- mongodb - Mongodb聚合数组分区和计数
- java - Wildfly 23/24 (Jakarta JWS) 中禁用了 WebServices 子系统
- google-cloud-platform - 如果不是为了模拟,“服务帐户用户”角色的意义何在?
- input - 为什么输入(colorPicker)只支持Hex?
- python - 尝试复制已经工作的代码,但在导入过程中遇到错误
- amazon-web-services - EKS aws-ebs-csi-driver 无法挂载卷
- dart - Dart Mixin 获取超字段值