提问者:小点点

如何用flask将内容加载到div元素中


我想用python函数的结果填充/更新index.html中的一个div区域,但我不知道如何做到这一点。 我知道还有其他几个类似主题的问题,但我没能成功回答,因为它们太具体了。 我要为这事拔头发了。
会是一个这么好的人来指导我吗?
这是main.py中的函数:

@app.route('/')
    
    def index():
        return render_template('index.html')
        
 @app.route('/stat/')
        
        def stat():
        
            a = 2
            b = 10
        
            return(str(a) + ' is not ' + str(b))

这是index.html:

<body>

    <form action="/stat/"> 

    <button type="submit" id="btn1" class="btn btn-primary btn-sm">check stat</button>

    </form>

 <div id="stat_content"></div>

</body>

共3个答案

匿名用户

正如@S3Dev所指出的,您将需要通过一个额外的参数将字符串传递给模板。 例如,我们可以这样做:

@app.route('/stat/', methods=['GET', 'POST']) # EDIT
    def stat():
        a = 2
        b = 10
        text = f"{a} is not equal to {b}"
        return render_template("index.html", text=text)

在上面的代码中,我们将text设置为要传递给模板的字符串。 在模板中,我们将能够以text的形式访问这个字符串变量。

现在,当呈现index.html时,它将查找从Flask应用程序传入的text变量。 这是由Jinja 2负责的,它是Flask使用的渲染引擎。

<div id="stat_content">
  {% if text %}
  <h2>No text to show</h2>
  {% else %}
  <h2>{{ text }}</h2>
  {% endif %}
</div>

使用带花括号的Jinja2语法,我们首先检查text变量是否存在; 如果它不存在,我们将呈现消息“没有文本显示”。 当我们第一次路由到“/”或Flask应用程序的默认home路由时,就会发生这种情况。

但是,一旦用户填写了表单,他们将被重定向到“/stat/”,此时我们将生成text并通过render_template(“index.html”,text=text)函数调用将其传递回index.html。 然后,当Jinja2呈现index.html时,它将看到text是从Flask应用程序传递过来的,并显示该消息,即2不等于10。

匿名用户

你想从按钮开始,对吗? 下面介绍如何使用Ajax实现这一点。。。

<body>
<form action="/stat/">
<button type="submit" onclick="GetData();" id="btn1" class="btn btn-primary btn-sm">check stat</button>
</form>
<div id="stat_content"></div>
</body>
<script type="text/javascript">
function GetData() {
var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == XMLHttpRequest.DONE) {   // XMLHttpRequest.DONE == 4
       if (xmlhttp.status == 200) {
           document.getElementById("stat_content").innerHTML = xmlhttp.responseText;
           }
           else if (xmlhttp.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    };

    xmlhttp.open("GET", "/stat/", true);
    xmlhttp.send();
}
</script>

匿名用户

要更新该div的内容,我认为(基于您的逻辑)您需要使用通过post请求提交的两个参数a和b执行对stat函数的ajax调用:

<form class="form-stat needs-validation" novalidate role="form">

  <div class="form-group">
    <input type="text" class="form-control" name="a" value="">
    <div class="invalid-feedback"></div>
  </div>
  
  <div class="form-group">
    <input type="text" class="form-control" name="b" value="">
    <div class="invalid-feedback"></div>
  </div>

  <button type="submit" id="btn1" class="btn btn-primary btn-sm">check stat</button>

</form>

<div id="stat_content"></div>

<script>
(function($) {
  "use strict";

  $('.form-stat').submit(function(e) {
    e.preventDefault();

    $.ajax({
      url: {{ url_for('stat') }},
      type: 'POST',
      cache: false,
      dataType: 'json',
      data: $('.form-stat').serialize(),
      success: function(data) {
        // console.log(data);
        $('.form-stat input[name=a]').val(''); # reset field
        $('.form-stat input[name=b]').val(''); # reset field
        $('#stat_content').html(data); # update div with the returned vlue
      }
    });
  }); 
})(jQuery);
</script>

您只需对stat函数进行少量更改,就可以通过post动态提交这两个参数,如下所示:

from flask import Flask, request, make_response
import json

@app.route('/stat', methods=['POST'])
def stat():
    if request.method == 'POST':
        a = request.form['a']
        b = request.form['b']
        # check if inputs are valid to work with ..
        res = str(a) + ' is not ' + str(b) if a != b else str(a) + ' and ' + str(b) + ' are equal.'
        resp = make_response(json.dumps(res))
        resp.status_code = 200
        return resp