簡體   English   中英

需要每 10 秒在 html 模板 td 標簽中使用 flask 更新 render_template 傳遞的值

[英]Need update value passed by render_template with flask in html template td tag every 10 seconds

我有這個:

@views.route('/')
def home():
    while True:
        try:
            token=getToken()
            if(token!='null' or token!=''):
                plazas=getInfo(token,id)
        except:
            print('Conection failed')
            time.sleep(secs)

        return render_template("home.html", plazas=plazas)

需要更新“plazas”變量值,它在我的 td 標簽上的 html 模板中使用“while True”循環不斷刷新:

{% 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 %}

我曾嘗試使用 javascript,但是當 10 秒過去時,它告訴我 {{plazas}} 的結果未定義。 有什么幫助嗎?

<script type="text/javascript">
window.onload = setInterval(refresh, 10000);
function refresh(places) {
    var elements = document.getElementsByClassName("num");
        for(let i = 0; i < elements.length; i++) {
            elements[i].innerHTML = places;
    }
    return elements[i].innerHTML = places;
}
</script>

要用新文本刷新它,您可以獲取到您自己的 flask 路由並使用setInterval更新信息

HTML

<td id="num" style="color:#39FF00">{{plazas}}</td>
<script>
var element = document.findElementById("num")
async function reload() {
  const promise = await fetch('/myroute')
  const data = await promise.text()
  element.innerHTML = data
}
window.onload = setInterval(reload, 1000)
</script>

Flask

@app.route('/myroute')
def myroute():
  # time is just an example
  return time.time()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM