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

-1 投票
1 回答
24 浏览
提问于 2025-04-14 15:50

我在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>

但是在终端上什么都没有打印出来,我的代码哪里出问题了?

我本来希望在终端上看到'im here'这个字符串的。

1 个回答

0

你可以在HTML中创建一个表单,然后像这样设置一个提交的路径:

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

app.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")

希望这能帮到你。不过,如果你想写一个函数来改变网页上的内容,你需要学习JavaScript。

撰写回答