【问题标题】:Pass variables from Flask (Python) to Javascript in a Separate JS file via AJAX [duplicate]通过AJAX将变量从Flask(Python)传递到单独的JS文件中的Javascript [重复]
【发布时间】:2021-10-23 00:30:08
【问题描述】:

我正处于学习阶段,所以请多多包涵。我一直在尝试得到答案,但通常它的 type="POST" 从 JS 通过 AJAX 到 Flask。

这是我的 app.py。

@app.route("/dashboard", methods=["GET","POST"]);
def dashboard():
    yearCount = #Sample list of dict data
    return render_template("dashboard.html", yearCount=yearCount)

(编辑)如何从上面获取 yearCount 并通过 AJAX 将其传递给 javascript? yearCount 将在dashboard.html 呈现时加载。

这是我的 js

$.ajax({
  url: '/dashboard',
  type: "GET",
  // data: "How do I get the data yearCount from /dashboard?",
  success: function() {
    alert(this.url);
  }
});

非常感谢您的帮助!整整一周都在扯我的头发,试图寻找答案。

【问题讨论】:

    标签: javascript python ajax variables flask


    【解决方案1】:

    在渲染过程中从模板传递变量:
    您可以使用 jinja 过滤器tojson 将变量作为 json 传递。如果您需要模板之外的变量,则必须将其作为参数传递。

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body>
        <script type="text/javascript">
          const yearCount = {{ yearCount | tojson }};
          console.log(yearCount);
        </script>
      </body>
    </html>
    

    当页面已经显示在浏览器中时加载数据:
    如果您想在模板渲染后再次接收变量,ajax 是正确的选择。

    from flask import jsonify
    
    @app.route('/count')
    def count():
        yearCount = # your dict data here.
        return jsonify(yearCount)
    

    在您的示例代码中,您使用的是jQuery 库。 然而,在fetch api 的帮助下实现也是可能的。以下是每个示例。

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body>
    
        <!-- Load the jQuery library. -->
        <script 
          src="https://code.jquery.com/jquery-3.6.0.min.js" 
          integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" 
          crossorigin="anonymous"></script>
        <!-- Use the jQuery library to load data with ajax. -->
        <script type="text/javascript">
          // jQuery ajax
          $.ajax({
            url: '/count'
          }).done((data) => {
            console.log(data);
          });
        </script>
    
    
        <!-- The fetch api does not require any additional library. -->
        <script type="text/javascript">
          // fetch api
          fetch('/count')
            .then(resp => resp.json())
            .then(data => console.log(data));
        </script>
    
      </body>
    </html>
    

    【讨论】:

    • 感谢您的回答!我仍然不清楚。您的所有代码都通过 html 中的脚本标记或单独的 javascript 文件运行?我跑了 $.ajax({ url: '/count' }).done((data) => { console.log(data); });在 js 中,但它说“$ 未定义。”
    • @JamesTan 抱歉,我试图更改我的答案以使其更易于理解。如果您仍有问题,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    • 2016-09-12
    • 2016-10-14
    • 1970-01-01
    • 2011-11-08
    • 2019-10-18
    相关资源
    最近更新 更多