【问题标题】:Is there a way to automatically update a webpage using Django?有没有办法使用 Django 自动更新网页?
【发布时间】:2022-01-26 06:52:53
【问题描述】:

我正在尝试使用 Django 在网页中创建倒数计时器。我在模板视图中进行了必要的时间计算,并将它们作为上下文传递给模板,并使用上下文显示它。但是,计时器只会在我刷新网页时更新。有什么办法可以让定时器自动更新?

模板的查看功能:

def home(request):
    #Time Calculations Performed Here
    time_dict={'days': days, 'hours': hours, 'minutes': minutes, 'seconds': seconds}

    context={'participants':participants, 'time':time_dict}
    return render(request, 'base/home.html', context)

显示计时器的模板部分:

<hr>
<h3>Countdown Timer</h3>
<div><h5>
    Days: {{time.days}}, Hours: {{time.hours}}, Minutes: {{time.minutes}}, Seconds: {{time.seconds}}
<h5></div>
<hr>

【问题讨论】:

    标签: python html django templating


    【解决方案1】:

    您可以在这里使用jQuery ajax,如下所示:

    views.py

    from django.http import JsonResponse
    
    def cal_time(request):
        #Time Calculations Performed Here
        time_dict={'days': days, 'hours': hours, 'minutes': minutes, 'seconds': seconds}
        return JsonResponse(timde_dict)
    

    home.html

    <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js">
    </script>
    <script>
      function getUpdatedTime(){
         $.ajax({url: "/cal_time/", success: function(result){
             var content = "Days: "+result['days']+", Hours: "+result['hours']+", Minutes: "+result['minutes']+", Seconds: "+result['seconds'];
             $("h5").text(content);
             setTimeout(function(){getUpdatedTime();}, 2000); // will call function to update time every 2 seconds
         }});
      }
      $(document).ready(function(){
         getUpdatedTime();
      });
    </script>
    

    【讨论】:

    • 谢谢。我希望不要进入 JS,但看起来那是不可能的。
    猜你喜欢
    • 2012-08-01
    • 2020-12-11
    • 2019-07-01
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多