Python 使用Django的HTML动态变量值

Python 使用Django的HTML动态变量值,python,html,django,dynamic,tags,Python,Html,Django,Dynamic,Tags,我希望在HTML文件中显示一个不断变化的python变量(从websocket服务器读取),目前我使用的是Django标记,如下所示: 模板标签/mytag.py from django import template register = template.Library() current_value = 0 @register.filter def c_value(placeholder): return current_value #more code that modifi

我希望在HTML文件中显示一个不断变化的python变量(从websocket服务器读取),目前我使用的是Django标记,如下所示:

模板标签/mytag.py

from django import template
register = template.Library()
current_value = 0

@register.filter
def c_value(placeholder):
    return current_value

#more code that modifies current_value reading from a websocket server
index.html

{% load mytag %}
<script>
function mytimer() {
  setInterval(function(){ 
                $('#stuff').html( {{ placeholder|c_value }} ); 
              }
              , 1000);
}
mytimer();
</script>

#some code from the website

<span id="stuff">Holder</span>
{%loadmytag%}
函数mytimer(){
setInterval(函数(){
$('#stuff').html({{占位符| c|u值}});
}
, 1000);
}
mytimer();
#网站上的一些代码
持有人
然而,自然地,{placeholder | c_value}}只输出“current_value”的第一个值,在本例中为0,因此index.html的源代码最终是:

在“{{placeholder | c_value}}”之后的源代码

<script>
function mytimer() {
  setInterval(function(){ 
                $('#stuff').html( 0 ); 
              }
              , 1000);
}
mytimer();
</script>

函数mytimer(){
setInterval(函数(){
$('#stuff').html(0);
}
, 1000);
}
mytimer();
这是不需要的,因为我们希望每秒打印“当前值”的变化值


对于这些动态文本,通常的方法是什么?非常感谢

要完成此行为,您需要做几件事

  • 设置一个URL,返回您感兴趣的值。例如,设置您的网站,使URL
    http://example.com/c_value
    返回包含正确信息的响应。通常最好以JSON格式返回响应;在Django中,您可以使用
    JsonResponse
    类来执行此操作。假设您返回文本:

    {
        "c_value": "foo"
    }
    
  • 更改您的页面,使其不会从模板加载变量,而是向您设置的地址发出请求。如果您使用的是jQuery,那么可以使用该函数来实现这一点(或者,这只是一个仅包含JSON数据的$.ajax的简写函数)。假设返回的JSON与我在步骤1中给出的示例相匹配,那么在计时器中可能会出现类似的结果。(
    data
    将包含从服务器发送的JSON对象)


  • 这解决了它,非常感谢!现在看起来很基本,但我对AJAX一无所知,现在一切都有了意义。记录在案:1。我为“/c_value”创建了一个视图,因此它“my_site/c_value”使用服务器2的相关数据回答了一个JSON。安装jQuery,然后使用AJAX从“/c_value”3获取前面提到的相关信息。用setInterval将这个AJAX模块从我之前指定的计时器插入函数,再次感谢!很高兴它对你有用!请记住,您需要发出AJAX请求——这只会减少编写代码的数量。
    $.ajax({
        dataType: "json",
        url: "http://example.com/c_value",
        success: function(data) {
            $('#stuff').html(data["c_value"]);
        }
    });