【问题标题】:Is there a way to distinguish between buttons pressed Flask有没有办法区分按下的按钮Flask
【发布时间】:2021-01-30 00:25:49
【问题描述】:

我正在用 python 创建一个 Flask 应用程序,但遇到了一个问题。

我只是想知道是否说您在 index.html 上有两个按钮,它们做不同的事情

假设你有一个这样的html文件

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>My Site!</title>
  </head>
  <body>
      <form action="#" method="post">

    <button type="submit">Somthing1</button>
    <button type="submit">Somthing2</button>
</form>
  </body>
</html>

还有这样的功能

@app.route("/", methods = ["GET", "POST"])
def home():
    if(request.method == "POST"):
        # Solution here
    return "Hello, World!"

我如何判断标记为“Somthing1”或“Something2”的按钮被按下了?

【问题讨论】:

  • 我的回答对您有帮助,请采纳,以便其他人看到您的问题已解决,更容易找到正确答案。

标签: python html flask


【解决方案1】:

首先,您需要为按钮命名。

<button type="submit" name="1">Somthing1</button>
<button type="submit" name="2">Somthing2</button>

然后,在你的 Python 代码中,你可以有这样的代码:

if(request.method == "POST"):
     one = request.form.get("1")
     two = request.form.get("2")
     if one is not None:
         # Do stuff for Somthing1
     elif two is not None:
         # Do stuff for Somthing2

request.form.get如果存在则返回元素,否则返回None

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多