2014-07-14 95 views
5

我目前正在尝试显示每5秒更新一次到SQLite数据库的值列表。Python烧瓶获取JSON数据显示

我可以设法通过使用下面的代码的结果转换为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> 

回答

2

你的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参数只是位置元素。

+0

Thankyou非常Martijn,它的工作很好,现在自动刷新:)。 – craigdabbs