代码之家  ›  专栏  ›  技术社区  ›  sK500

从flask传递到JS的值是html格式的,而不是静态的

  •  0
  • sK500  · 技术社区  · 3 年前

    我需要调用一个javascript函数 say_hello 存在于 static 文件夹和通行证 Hello 作为消息显示为警报。以下是我的工作:

    app.py

    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    
    @app.route('/')
    def hello():
        return render_template('index.html', data={'message': 'Hello'})
    
    
    if __name__ == '__main__':
        app.run()
    

    这是有效的:

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <script>
        const message = {{data.message|tojson|safe}}
            alert(message);
    </script>
    </body>
    </html>
    

    这不管用:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <script src="/js/hello.js">
        const message = {{data.message|tojson|safe}}
            say_hello(message);
    </script>
    </body>
    </html>
    

    hello.js

    function say_hello(message){
        alert(message)
    }
    

    JS控制台没有显示任何问题,也没有显示消息,只是一个空白页面。

    1 回复  |  直到 3 年前
        1
  •  1
  •   Tim Roberts    3 年前

    <script> 标签上有一个 src ,其内容被忽略。一个或另一个。

    <script src="/js/hello.js">
    </script>
    <script>
        const message = {{data.message|tojson|safe}}
            say_hello(message);
    </script>