2014-07-14 3 views
5

현재 5 초마다 sqlite 데이터베이스에 업데이트되는 값 목록을 표시하려고합니다.Python Flask가 표시 할 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 %} 

하지만 난 포인터 필요 해요.

SOLVED !!

새로운 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 객체가됩니다. ,이 정확히 $.ajax() 호출과 동일하지

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

을하지만 당신은 typedataType 매개 변수를 생략 할 수 : 당신이 GET 요청을 통해 JSON을로드하기 때문에

, 당신은뿐만 아니라 jQuery.getJSON() method 여기에 사용할 수있다 urlsuccess 매개 변수는 단지 위치 요소입니다.

+0

대단히 Martijn, 자동 새로 고침과 함께 매우 잘 작동합니다. :) – craigdabbs

관련 문제