使用Flask将JavaScript连接到Python脚本 [英] Connect JavaScript to Python script with Flask

查看:62
本文介绍了使用Flask将JavaScript连接到Python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全用HTML/CSS创建了一个网站.还可以使用Javascript进行事件(单击按钮,...).

I created an website with HTML/CSS completly on my own. Also use Javascript for events (click on button, ...).

现在我想用它连接一个python脚本,更重要的是,将python的结果返回到我的网站并在那里显示(使用)它们.考虑这样的事情:

Now i want to connect an python script with it and more important, return the results from python to my website and display (use) them there. Consider something like this:

带有输入和按钮的网站.如果单击该按钮,则应运行python脚本,如果输入的是奇数或偶数,则该python脚本将返回(当然,在这种情况下,您不需要python,但我想这样做)

Website with an input and button. If you click on the button a python script should run which returns if the input is an odd or even number (of course you dont need python for this specific case, but i want to do that)

根据我的研究,我相信Flask是执行此操作的库(?),但我真的不知道该怎么做.我发现的例子很少.如果有人可以实现上面的示例或告诉我如何正确执行操作,我将不胜感激.

From my research i believe Flask is the library to do it (?), but i really dont know how to do it. I found very few examples. I would really appreciate if someone could implement the above example or tell me how to do it exactly.

我知道在线上已经有关于该概念的一些问题了,但是正如我所说的那样,例子很少.

I know there are already some questions about that concept here online, but as i said, with very few examples.

推荐答案

非常感谢您的帮助和所花费的时间.但是您的回答并没有以我需要的方式帮助我.那时我不知道该怎么办,但自从前一段时间(我观看了youtube视频...)弄清楚了以后,我以为我在这里分享我的解决方案(粘贴两个字符串):

I really appreciate your help and time spent. But your answer did not help me in the way I needed it. At that point I had no clue what to do but since I figured it out some time ago (I watched an youtube video...) I thought i share my solution here (stick two strings):

那是app.py:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/stick', methods=['GET', 'POST'])
def stick():
    if request.method == 'POST':
        result = request.form['string1'] + request.form['string2']
        return render_template('index.html', result=result)
    else:   
        return render_template('index.html')

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

然后是index.html(放入模板文件夹):

And that index.html (put in the folder templates):

<!DOCTYPE html>
<html>
<body>
    <h3> Stick two strings </h3>
    <form action="{{ url_for('stick') }}" method="post">
            <input type="text" name="string1">
            <input type="text" name="string2">
            <input type="submit" value="Go!">
            <p id="result"></p>
    </form>
<script>

document.getElementById("result").innerHTML = "{{result}}"

</script>
</body>
</html>

在终端中输入 python app.py ,它应该可以正常工作.

In the terminal type in python app.py and it should work.

这篇关于使用Flask将JavaScript连接到Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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