![](/img/trans.png)
[英]how to change the variable value in Javascript after every 30 seconds
[英]How can i get refreshed value of flask variable with JS and show in HTML template every 30 seconds?
这是一个停车应用程序,每 30 秒刷新一次可用的停车位,而无需刷新页面。
这是带有路由和渲染模板的 my.py
@views.route('/')
def home():
while True:
try:
token=getToken()
if(token!='null' or token!=''):
plazas=getInfo(token,parkingID)
except:
print('Error en la conexion')
time.sleep(secs)
return render_template("home.html", plazas=plazas)
我的 HTML 是:
<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>
还有我的 JS:
var elements = document.getElementsByClassName("num");
function refresh(pl){
elements.innerHTML = pl;
}
我的问题是 {{plazas}} 变量总是采用初始值并且不会每 30 秒更新一次,即使我在 my.py 中使用 while true: 循环也是如此。 有什么帮助吗?
一个简单的解决方案是通过使用await fetch()
从 javascript 获取数据来获取数据。 然后,您可以使用setInterval()
设置更新程序。
Flask
@app.route('/refresh')
def refresh();
try:
token=getToken()
if(token!='null' or token!=''):
plazas=getInfo(token,parkingID)
except:
return "Error refreshing!"
Javascript
var element = document.getElementsByClassName("num")
async function reload() {
// make a request to reload
const promise = await fetch("/refresh")
// get the text from the request, alternatively you can also use .json() to
// retrieve json
const text = await promise.text()
element.innerHTML = text
}
// refresh every 30 seconds
window.onload = setInterval(reload, 30000)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.