【问题标题】:Python Flask get json data to displayPython Flask 获取要显示的 json 数据
【发布时间】:2014-09-04 07:50:39
【问题描述】:

我目前正在尝试向 sqlite 数据库显示每 5 秒更新一次的值列表。

我可以使用以下代码将结果转换为 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>

【问题讨论】:

    标签: jquery python json flask


    【解决方案1】:

    您的 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() method

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

    这与$.ajax() 调用完全相同,但您可以省略typedataType 参数,而urlsuccess 参数只是位置元素。

    【讨论】:

    • 非常感谢 Martijn,它现在可以很好地使用自动刷新:)。
    猜你喜欢
    • 2020-05-09
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多