如何在flask应用程序的同一页面上发布输出结果? [英] How to post the output result on the same page in flask app?

查看:114
本文介绍了如何在flask应用程序的同一页面上发布输出结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个flask应用程序,该应用程序将一些文本作为输入,运行python脚本,并在同一html页面上吐出输出,除了它会转到新页面.我不知道为什么会转到新页面.

I have a flask app that takes some text as an input, runs a python script and spits out an output on the same html page, except it goes to a new page. I don't see why it would go to a new page.

这是我的app.py文件:

This is my app.py file:

#!/usr/bin/env python3

from flask import *
from flask import render_template
from myclass import myfunction

app = Flask(__name__)

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

@app.route('/', methods= ["POST"])
def background_process():
    if request.method == 'POST':
        try:
            story = request.form.get('story')
            if story:
                result = myfunction(story)
                return render_template('index.html', **jsonify(result))
            else:
                return jsonify(result='Input needed')
        except Exception as e:
            return (str(e))

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

这是我的index.html文件:

And this is my index.html file:

 <!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="../static/main.css">
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script type=text/javascript>
            $(function() {
              $('a#process_input').bind('click', function() {
                $.getJSON('/background_process', {
                  story: $('textarea[name="story"]').val(),
                }, function(data) {
                  $('#result').text(data.result);
                });
                return false;
              });
            });
        </script>
    </head>

    <body>
        <div class='container'>
            <form>
                <textarea id="text_input" rows="20" cols="80" name=story></textarea>
                <br>
                <a href=# id=process_input><button class='btn btn-default'>Submit</button></a>
            </form>
            <br>
            <p><h2 align='center'>Result:</h2><h2 id=result align='center'></h2></p>

        </div>
    </body>
</html>

给出输入后,它将以json格式在新页面中显示结果.我想在同一页面上显示它.这是怎么了 谢谢!

When input is given, it shows the result in a new page on json format. I want to show it on the same page. What's going wrong here? Thanks!

推荐答案

由于您已经在使用ajax方法来处理响应,因此您可以直接返回JSON响应,而无需呈现新模板:

As you are already using an ajax method able to handle the response, you could return the JSON response directly instead of rendering a new template:

return jsonify(result=result) 

另外,您可能希望将jQuery方法的GET更改为POST:

Also you may want to change GET to POST for the JQuery method :

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="../static/main.css">
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script type=text/javascript>
            $(function() {
              $('a#process_input').bind('click', function() {
                $.post('/', {  
                  story: $('textarea[name="story"]').val(),
                }, function(data) {
                  $('#result').text(data.result);
                });
                return false;
              });
            });
        </script>
    </head>

(请注意,如果您保留两个分开的功能,而不是我在下面建议的功能,则需要编写$.post('/background_process'.)

(Note that you need to write $.post('/background_process' if you keep two separated functions, and not the one i suggest below.)

然后,您可以在一个函数中收集代码,模板将使用GET方法呈现,并且响应将从POST呈现:

Then you can gather the code in one function, the template will be rendered with a GET method, and the response will be rendered from a POST :

app = Flask(__name__)

@app.route('/', methods= ["GET", "POST"])
def homepage():
    if request.method == 'POST':
        story = request.form.get('story')
        if story:
            result = myfunction(story)
            return jsonify(result=result)
        else:
            return jsonify(result='Input needed')

    return render_template('index.html')

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

这篇关于如何在flask应用程序的同一页面上发布输出结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆