每60秒Python Flask刷新表

时间:2017-08-16 18:42:46

标签: javascript python ajax flask javascript-events

我在下面贴了我的烧瓶代码。我想每60秒刷新一次表数据。 Setinterval函数包含在html中。但是它并不令人耳目一新。我没有在ajax / javascript中找出确切的问题。请有人帮忙解决问题。

App.py:

app = Flask(__name__)
app.config['SECRET_KEY'] = 'dsfd'
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'pwd'
app.config['MYSQL_DATABASE_DB'] = 'db'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
eachcur = ["A","B","C","D"]

@app.route('/', methods= ['GET'])     
def display_deals():


    conn = mysql.connect()
    c = conn.cursor()
    data = ((),)
    for curren in eachcur:
      query = "SELECT * from "+curren+" ORDER BY Currid DESC LIMIT 1"
      c.execute(query)
      data = data + c.fetchall()

    conn.close()


    return render_template("dashboard.html", data=data)

if __name__ == '__main__':
    app.run(debug=True)

dashboard.html:

<!doctype html>
<html>
 <body>
<script>
 setInterval(function() {
 $.ajax({
  type: "POST",
  url: "/",
 })
  .done(function( data ) {
    $("#table-box").val(data)
   });
  }, 1000 * 60); 
  </script>
<table border="2" cellpadding="4" cellspacing="5" id="table-box" >
{% for row in data %}
    <tr>
    {% for d in row %}
        <td>{{ d }}</td>
    {% endfor %}
    </tr>
{% endfor %}
</table>
 </body>
</html>

控制台输出:

jquery.min.js:4 XHR finished loading: POST "http://localhost:5000/".
send @ jquery.min.js:4
ajax @ jquery.min.js:4
(anonymous) @ (index):7
setInterval (async)
(anonymous) @ (index):6
17:21:45.516 jquery.min.js:4 [Violation] 'load' handler took 334ms

Console snapshot

Console snapshot - 2 谢谢

1 个答案:

答案 0 :(得分:2)

您的代码存在一些问题:

  1. 您正在使用.val().html()

    .val()用于设置输入字段之类的值,而不是覆盖整个DOM对象。您应该在此使用.html()

  2. 您正在将非HTML数据分配给#table-box

    生成表的for语句仅在页面加载时运行。您需要重新生成AJAX .done()处理程序中的所有表行。

  3. 请参阅下面的示例,修复了这两个问题。

    <!doctype html>
    <html>
     <body>
    <script>
     setInterval(function() {
     $.ajax({
      type: "POST",
      url: "/",
     })
      .done(function( data ) {
        console.log(data);
        var tableHtml = '';
        for (row in data) {
          tableHtml += '<tr>';
          for (d in row) {
            tableHtml += '<td>' + d + '</td>';
          }
          tableHtml += '</tr>';
        }
        $("#table-box").html(tableHtml)
       }).fail(function(jqXHR, textStatus, errorThrown) {
         console.log(jqXHR, textStatus, errorThrown);
       });
      }, 1000 * 60); 
      </script>
    <table border="2" cellpadding="4" cellspacing="5" id="table-box" >
    {% for row in data %}
        <tr>
        {% for d in row %}
            <td>{{ d }}</td>
        {% endfor %}
        </tr>
    {% endfor %}
    </table>
     </body>
    </html>
    

    编辑:看起来你没有路由/控制器设置对POST /的AJAX请求的句柄。你应该尝试这样的事情:

    @app.route('/json', methods= ['GET'])     
    def display_deals_json():
      conn = mysql.connect()
      c = conn.cursor()
      data = ((),)
      for curren in eachcur:
        query = "SELECT * from "+curren+" ORDER BY Currid DESC LIMIT 1"
        c.execute(query)
        data = data + c.fetchall()
      conn.close()
      return json.dumps(data)
    

    您需要将AJAX命令更新为:

    $.ajax({
      type: "GET",
      url: "/json",
    })