Flask+AJAX+Jquery+JINJA to dynamically update HTML Table

风流意气都作罢 提交于 2021-01-18 04:45:21

问题


I want to display the Port status dynamically. I don't want to reload the page to see a new value. I know how to get the Port status in Python(using uiApi()). Right now I render a template with the value and show the values in HTML table. How can I continually update the table with a value from Flask? I have the AJAX and jquery available.

The Flask Code is give below:

    @app.route('/')
    def show_auth():
       tData = uiApi()
       ..

       return render_template('show_auth.html', tMain=tData)

The {{field}} in The HTML file 'show_auth.html' below should be dynamically updated:

<form   action="{{ url_for('submit_token') }}" method=post>
  <div id="Main" class="tabcontent" style="display:block" >
    <div class="PanelWrapper" >
      <div class="pageTitle">WAN</div>
      <div class="layout">
        <div class="col">
          <table frame="void" rules="none">
            <tbody>
              {%for key, field in tMain.items() %}
              <tr>
                <td class="attrLabel" valign="middle" nowrap>{{key}}</td>
                <td class="attrLabel" valign="middle">:&nbsp;</td>
                <td>{{field}}</td>
              </tr>
              {% endfor %}
            </tbody>
          </table>
        </div>
...
....

回答1:


You will need two things : A route for an AJAX request that will return your data formatted as JSON (should be quite easy to do with Flask's jsonify function).

Once you have that route setup, you need to call it using an AJAX call. Using jQuery it feels painless (but you can do it with vanilla JS too).

<script>
    $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
    (function(){
        $.getJSON(
            $SCRIPT_ROOT+"/_stuff", // Your AJAX route here
            function(data) {
                // Update the value in your table here
            }
        );
        setTimeout(arguments.callee, 10000);
    })();
</script>

In the snippet above you will need to specify the path of your AJAX route, and do things with the data value. For a quick test you can simply console.log(data) and check if the returned data are good.

Note that the above snippets uses an anonymous function, and will fetch your data every 10 seconds (10000 ms).

I hope that will help

Documentation :
Ajax with Flask
jQuery.getJSON



来源:https://stackoverflow.com/questions/40804245/flaskajaxjqueryjinja-to-dynamically-update-html-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!