Python Flask 获取并显示 JSON 数据

8 投票
1 回答
11711 浏览
提问于 2025-04-18 13:13

我现在正在尝试每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>

相关问题:

1 个回答

4

你的AJAX请求应该会自动识别JSON格式的响应,不过明确告诉jQuery也没坏处:

$.ajax({
    type: "GET",
    url: $SCRIPT_ROOT + "_status",
    dataType: 'json',
    success: function(data) {
        $('#Result').text(data);
    }
);

contentType这个参数只在POST请求中使用,它告诉服务器你发送的数据是什么类型。

data对象包含了你用Flask的jsonify()返回的内容;在这个例子中,它会是一个包含BoilerRoom等键的JavaScript对象。

因为你是通过GET请求加载JSON数据,你可以直接使用jQuery.getJSON()方法

$.getJSON(
    $SCRIPT_ROOT + "_status",
    function(data) {
        $('#Result').text(data);
    }
);

这个方法和$.ajax()调用的效果是一样的,不过你可以省略typedataType这两个参数,而urlsuccess参数只是位置参数。

撰写回答