我目前正在尝试显示每5秒更新一次到sqlite数据库的值列表。
我可以使用以下代码将结果转换为JSON格式:
@app.route('/_status', methods= ['GET', 'POST'])
def get_temps():
db = get_db()
cur = db.execute('select sensor_name, temp from cur_temps ORDER BY sensor_name')
#cur_temps = cur.fetchall()
return jsonify(cur.fetchall())
通过浏览器导航到网页返回
{
"BoilerRoom": 26.44,
"Cylinder1": 56.81,
"Cylinder2": 39.75,
"Cylinder3": 33.94
}
我希望定期在网页上更新这些数据,而不重新加载整个网页。我在第一个跨栏时卡住了,无法显示实际数据。
我使用的HTML代码是
{% extends "layout.html" %}
{% block body %}
<script type=text/javascript>
$(function() {
$("#submitBtn").click(function() {
$.ajax({
type: "GET",
url: $SCRIPT_ROOT + "_status",
contentType: "application/json; charset=utf-8",
success: function(data) {
$('#Result').text(data.value);
}
});
});
});
</script>
<strong><div id='Result'></div></strong>
{% endblock %}
我从示例中选择了代码,但我需要一个指针。
解决了的!!
新HTML代码
<script type=text/javascript>
function get_temps() {
$.getJSON("_status",
function (data) {
$('#Cyl1').text(data.Cylinder1)
$('#Cyl2').text(data.Cylinder2)
$('#Cyl3').text(data.Cylinder3)
$('#BRoom').text(data.BoilerRoom);
}
);
}
setInterval('get_temps()', 5000);
</script>
<table id="overview">
<tr>
<th>Location</th>
<th>Temperature</th>
</tr>
<tr>
<td>Cylinder Top</td>
<td id="Cyl1"></td>
</tr>
<tr>
<td>Cylinder Middle</td>
<td id="Cyl2"></td>
</tr>
<tr>
<td>Cylinder Bottom</td>
<td id="Cyl3"></td>
</tr>
<tr>
<td>Boiler Room</td>
<td id="BRoom"></td>
</tr>
</table>
最佳答案
您的Ajax调用应该自动检测到JSON响应,但是明确地告诉jquery它不会有什么影响:
$.ajax({
type: "GET",
url: $SCRIPT_ROOT + "_status",
dataType: 'json',
success: function(data) {
$('#Result').text(data);
}
);
contentType
参数仅用于POST请求,告诉服务器您发送的数据类型。data
对象包含您的flaskjsonify()
响应返回的任何内容;在本例中,它将是一个带有BoilerRoom
等键的javascript对象。由于您是通过GET请求加载JSON,因此您也可以在此处使用
jQuery.getJSON()
method:$.getJSON(
$SCRIPT_ROOT + "_status",
function(data) {
$('#Result').text(data);
}
);
这与
$.ajax()
调用完全相同,但您可以忽略type
和dataType
参数,而url
和success
参数只是位置元素。