如何在 jinja/flask 按钮中使用 onClick 调用函数

问题描述 投票:0回答:1

我在 main.py 中有这条路线:

@app.route('/')
def home():
    
    def remove_book():
        print('im here')
    
    return render_template('index.html', books=Books.query.all(), rem_book=remove_book)

所以,我尝试在我的index.html文件的按钮中调用remove_book函数:

<button class="btn btn-danger btn-sm" onclick={{rem_book}}>X</button>

终端中没有打印任何内容,我的代码有什么问题吗?

我期望终端上打印“我在这里”字符串

python flask jinja2
1个回答
0
投票

您可以在 HTML 中创建一个表单并创建一个帖子路由,如下所示: 索引.html

<form action="/" method="POST">
<button type="submit">click me</button>
</form>

应用程序.py

from flask import Flask,render_template,request

def myfunc():
    for i in range(5):
        print("Hello world!")
    return 0

app = Flask(__name__)
@app.route("/",methods=["POST","GET"])
def index():
    if request.method == "POST":
        #this will where you will call your function
        myfunc()

        # visit form documentation https://tedboy.github.io/flask/generated/generated/flask.Request.html
        return """<script>alert("You've run the function!");window.location.assign('/')</script>""""
    return render_template("index.html")

我希望这能解决您的问题。但是如果你要做一个改变DOM内容(网页)的函数,你需要学习JS。

© www.soinside.com 2019 - 2024. All rights reserved.