从Python Flask函数中的HTML调用/调用JavaScript函数

5

我正在创建一个 Flask 应用程序,并尝试调用一个 Python 函数,在该函数中,我想要调用一些有关我在最初的 app.route('/') 中返回的 HTML 模板的 JavaScript 函数/代码。

如果用户进行了某些操作,则我将调用另一个函数,该函数应该调用一个 JS 函数。我已经在各处寻找了解决方案,但是我无法理解任何解决方案。

这是我的代码结构:

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        #verify if the file is valid
        #here invoke js to do something (for example flash("test"))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''
2个回答

7
你可以在加载时执行JavaScript函数,并让函数检查条件。您可以通过使用Python更改条件来影响此检查的结果。如果您使用Flask的render_template函数,则不必在Python文件中编写HTML代码。出于更好的可读性,我正在使用此功能,但您始终可以将HTML代码放入Python代码中,就像以前一样。
您的HTML模板,例如命名为upload.html:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Upload new File</title>
</head>
<body onload="flashMessage()">
  <script>
    function flashMessage() {
      if ("{{ flash_message }}" == "True") {
        alert("[YOUR_MESSAGE_HERE]");
      }
    }
  </script>

  <h1>Upload new File</h1>
  <form method=post enctype=multipart/form-data>
    <input type=file name=file>
    <input type=submit value=Upload>
  </form>
</body>
</html>

你的Python代码:

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        #verify if the file is valid
        #here invoke js to do something (for example flash("test"))
        return render_template('upload.html', flash_message="True")

    return render_template('upload.html', flash_message="False")

因此,您HTML文件中的条件行将呈现为:
if ("True" == "True")

或者

if ("False" == "True")

根据您是否想要显示闪存消息来决定。


1
你只需要向 render_template 函数传递一个参数,例如 "flash_message"。
from flask import Flask, render_template

app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    # YOUR CODE...

    return render_template('upload.html', flash_message=True)

然后您可以检查 flash_message 参数是否为 True,如果满足条件,则加载 js,否则不加载。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Upload new File</title>
</head>

<body>
    {% if flash_message %}
    <script>
        function YourFunction() {
            alert("[YOUR_MESSAGE_HERE]");
        }
    </script>
    {% endif %}

    <h1>Upload new File</h1>

    <form method=post enctype=multipart/form-data>
        <input type=file name=file>
        <input type=submit value=Upload>
    </form>
</body>

</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接