首页 > 解决方案 > 在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})

标签: jquerydjango

解决方案


推荐阅读