javascript - 使用 Flask 进行表单处理

标签 javascript python flask

我知道这可能是微不足道的,但我似乎无法弄清楚如何将用户在我的网页上提交的数据发送到服务器端。我正在制作一个简单的 Web 应用程序,它接收用户的单词,然后使用 Python 计算服务器端的音节数。

我使用flask渲染页面:

@app.route('/')
def hello():
  webPage = open('pg.html','r')
  return webPage.read()

JavaScript中,我有一个表单:

<form method="get"><br><br> 
  Enter a Word: <br>
 <input type="text" name="name"><br><br>
 <input type="submit" value="Submit">
         </form>

当用户向此表单提交单词时,如何使用 Python 检索它?

我已经阅读了有关 GET POST 方法的内容,但我仍然很困惑。

最佳答案

考虑到您了解 GETPOST,这里是重要的部分。

显示主页(你好)页面

from flask import render_template

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

现在,在 hello.html 中(注意操作和方法):

<html>
    <head></head>
    <body>
        <form method="POST" action="/testpost">
            Enter a Word: <br>
            <input type="text" name="name"><br><br>
            <input type="submit" value="Submit">
        </form>
    </body>
</html>

如果您注意到,该方法是POST,这意味着您的数据将以POST 形式发送到服务器。现在要处理 POST 请求,我们可以考虑以下内容:

现在进行 POST 处理

@app.route('/testpost', methods = ['POST'])
def postTesting():
    name = request.form['name']
    print name #This is the posted value

你看,request.form包含解析后的表单数据。

关于javascript - 使用 Flask 进行表单处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30330765/

相关文章:

javascript - javascript中的两个嵌套循环有什么区别?

javascript - 不分阶段工作。正常吗?

python - 当我使用 * 时语法无效

python - 编写/解析 Apple Motion 5 .motn 文件

python - manage.py 是组织/编写 Flask 应用程序的正确方法吗?

python - 从数据文件启动 postgres 数据库服务器

javascript - 不变违规 : requireNativeComponent: "BVLinearGradient"

javascript - 确认 asp.net 按钮后触发回发警报

python - 要计算每个 'option' 和 'Type' 每年出现的次数,

Python SQLAlchemy 类型错误 : unhashable type: 'dict' when trying to instantiate model with one-to-many relationship