使用python flask在同一页面中显示结果

时间:2019-07-08 13:01:18

标签: python flask jinja2

我正在使用python flask将表单数据发送到另一个HTML模板中。我需要在存在HTML输入表单的同一页面中显示结果。当前响应正在转发到下一页。

我试图通过JQuery运行,但仍然无法获得结果。

app.py

from flask import Flask, render_template, request
app = Flask(__name__)

@app.route('/')
def student():
   return render_template('index.html')

@app.route('/result',methods = ['POST', 'GET'])
def result():
   if request.method == 'POST':
      result = request.form
      return render_template("result.html",result = result)

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

index.html

<html>
   <body>
      <form action = "http://localhost:5000/result" method = "POST">
         <p>Name <input type = "text" name = "Name" /></p>
         <p>Physics <input type = "text" name = "Physics" /></p>
         <p>Chemistry <input type = "text" name = "chemistry" /></p>
         <p>Maths <input type ="text" name = "Mathematics" /></p>
         <p><input type = "submit" value = "submit" /></p>
      </form>
   <div>
   </div>
    </body>
</html>

Result.html

<!doctype html>
<html>
   <body>
      <table border = 1>
         {% for key, value in result.items() %}
            <tr>
               <th> {{ key }} </th>
               <td> {{ value }} </td>
            </tr>
         {% endfor %}
      </table>
   </body>
</html>

现在结果显示在result.html上,我需要将其显示在index.html上。请提出如何实现这一目标的建议。

2 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,可以看到多种方式:

1)
您可以将result.html包含在index.html中。
然后,您只需将结果数据传递到render_template函数中即可。
详细了解模板here

它看起来像这样:

{% include 'result.html' %}

index.html
中 并且result.html如下所示:

<div id="result_div">
  some code
</div>

2)
您可以使用AJAX发布表单数据,在flask中生成html,将其作为AJAX结果传递并通过javascript使用它更新页面。

$.ajax({
                        type: 'POST',
                        url: '/result',
                        data: JSON.stringify({
                            'data' : data,
                        }),
                        contentType: 'application/json;charset=UTF-8',
                        success: function(response){
                            // fill with html
                            $('#result_div').html(response.result);

                        },
                        error: function(error) {
                            // console.log(error);
                        }
                    });

当然,您也必须在/results上更新烧瓶代码。

在两种情况下,您都希望有一个页面(可以包含多个html文件)。

答案 1 :(得分:0)

我知道这是一个较老的问题,但对于其他可能感兴趣的人来说。你所要做的就是改变

return render_template("result.html",result = result)

return render_template("index.html",result = result)

或您可能想要返回的任何其他页面。 Render_template 只返回您要求的任何内容,如果您只想返回数据,或者您可以说的其他内容

return (data)

或者不管你的数据叫什么。

相关问题