向Flask render_template端点发出客户端POST请求

时间:2019-07-05 10:21:14

标签: javascript python html flask

长时间在这里和网络上搜索后,我找不到我需要的东西。这是我的问题的精炼而成的最小可验证示例。

要设置问题的背景,这是我打算实现的实际用例。端点/heatmap上有一个热图,用户可以单击单元格,并将其重定向到其他端点/more-info-on-cell。根据单击的单元格,用户将获得不同的结果。我几乎得到了预期的结果。唯一的问题是该页面不能真正正确地呈现,因为/more-info-on-cell的javascript由于某种原因未执行。

以下是此示例所需的文件夹结构:

root
|-templates
|  -index.html
|  -page.html
|-index.py

这是文件: index.html

  <!DOCTYPE html>
  <html>
  <head> 
  <title>Title of the document</title> 
  </head>

  <body>
      <a id="clickMe" style="cursor: pointer">Click here to send POST to render template on the backend</a>
  </body>

  <script 
    src="https://code.jquery.com/jquery-3.4.1.min.js" 
    integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" 
    crossorigin="anonymous"></script>
  <script>
      $(document).ready(function() {
          $("#clickMe").on('click', function() {
              console.log('clicked, making a request')

              $.ajax({
                  type: 'POST',
                  url: '/',
                  data: JSON.stringify({}),
                  contentType: 'application/json',
                  success: function(response) { window.document.write(response);  }
              })
          })
      })
  </script>

  </html>

page.html

 <!DOCTYPE html>
 <html>
 <head>
 <title>Title of the document</title>
 </head>

 <body>
 The content of the document......
 </body>

 <script
   src="https://code.jquery.com/jquery-3.4.1.min.js"
   integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
   crossorigin="anonymous"></script>
     <script>
         $(document).ready(function() {
             alert('the doc is ready');
         })
     </script>

 </html>

index.py

 #!/usr/bin/env python3
 from flask import Flask, request, render_template, jsonify
 app = Flask(__name__)

 @app.route("/", methods=["GET", "POST"])
 def index():
     if request.method == "GET":
         return render_template('index.html')
     elif request.method == "POST":
         return render_template('page.html')

您可以验证是否单击了index.html中的链接,您已成功重定向到page.html,但从未执行其javascript。因此,您永远不会收到我们在page.html中定义的警报。

应该通过与此处的flask后端完全配合来解决问题,因为在我的实际用例中,模板中也包含jinja变量。如果您通过form发出具有正确网址和操作为POST的方法的请求,则一切工作都将正常进行。虽然,一旦我开始发出javascript客户端POST请求,它的工作方式就可以到达正确的页面,但是它呈现的方式不正确,而且文档准备就绪的javascript也从未执行过。

1 个答案:

答案 0 :(得分:0)

对于也有这种用例的任何人,请确保您使用如下所示的方法post(在这种情况下,将其放入index.html中):

  <script>
      $(document).ready(function() {
          $("#clickMe").on('click', function() {
              console.log('clicked, making a request')

             post('/', {'key-1': 'val-1'});
          })
      })

 function post(path, params, method='post') {
     const form = document.createElement('form');
     form.method = method;
     form.action = path;

     for (const key in params) {
         if (params.hasOwnProperty(key)) {
             const hiddenField = document.createElement('input');
             hiddenField.type = 'hidden';
             hiddenField.name = key;
             hiddenField.value = params[key];

             form.appendChild(hiddenField);
         }
     }

     document.body.appendChild(form);
     form.submit();
 }
  </script>

这会在网页上创建一个隐藏的表单,然后提交表单,然后,flask会正确处理所有事情。