【问题标题】:How can i get refreshed value of flask variable with JS and show in HTML template every 30 seconds?How can i get refreshed value of flask variable with JS and show in HTML template every 30 seconds?
【发布时间】:2022-12-01 20:33:14
【问题描述】:

This is a parking app which refresh the available parking slots every 30 seconds WITHOUT refreshing page.

This is my .py with the route and render template

@views.route('/')
def home():
    while True:
        try:
            token=getToken()
            if(token!='null' or token!=''):
                plazas=getInfo(token,MercadoAbastos)
        except:
            print('Error en la conexion')
            time.sleep(secs)      
                return render_template("home.html", plazas=plazas)

My HTML is:

  <script  src="{{ url_for('static', filename='js/main.js') }}"></script>
 <script type="text/javascript">
    myVar = setInterval(refresh,30000,{{plazas}});
  </script>
</head>
<title>Home</title>
</head>
    <body>
        <table>
            {% for parking in parkings %}
                <tr>
                    <td class="par"><img src={{parking.image}} alt="img"></td>
                    <td class="nombre">{{parking.nombre}}</td>
                    {% if plazas|int >= (totalplazas*30)/100 %}
                    <td class="num" style="color:#39FF00">
                    {{plazas}}</td>
                    {% elif plazas|int < 1%}
                    <td class="num" style="color:red"><p class="an">COMPLETO</p></td>
                    {% elif plazas|int <= (totalplazas*10)/100%}
                    <td class="num" style="color:red">
                    {{plazas}}</td>
                    {% else %}
                    <td class="num" style="color:yellow">
                    {{plazas}}</td>
                    {% endif %}
                    <td class="dir"><img src={{parking.direccion}} alt="img"></td>
                </tr>
            {% endfor %}
        </table>
    </body>
</html>

And my JS:

var elements = document.getElementsByClassName("num");
function refresh(pl){
    elements.innerHTML = pl;
}

My problem is that the {{plazas}} variable always takes the initial value and is not updated every 30 seconds even if i use while true: loop in my .py. Any help?

【问题讨论】:

    标签: javascript python html flask jinja2


    【解决方案1】:

    You'll probably need to handle that using JavaScript. There are plenty frameworks that should enable this. Consider looking for popular solutions, like React.

    【讨论】:

      猜你喜欢
      • 2021-07-18
      • 2022-12-01
      • 2022-12-02
      • 2022-12-02
      • 2022-12-27
      • 2022-12-27
      • 2022-12-19
      • 2022-12-04
      • 2022-12-26
      相关资源
      最近更新 更多