【问题标题】:Make a client POST request to Flask render_template endpoint向 Flask render_template 端点发出客户端 POST 请求
【发布时间】:2019-07-05 10:21:14
【问题描述】:

在这里和网上搜索了很长时间后,我找不到我需要的东西。这是我的问题的一个提炼的最小可验证示例。

要设置问题的背景,这是我打算实现的实际用例。端点/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 中定义的警报。

这个问题应该通过在这里完全使用烧瓶后端来解决,因为我实际用例中的模板也有 jinja 变量。如果您通过 form 使用具有正确 url 且操作为 POST 的方法发出请求,一切都会完美运行。虽然,一旦我开始发出 javascript 客户端 POST 请求,它的工作原理就是我到达了正确的页面,但它呈现不正确 + 文档准备好的 javascript 永远不会被执行。

【问题讨论】:

  • 我想一种解决方案,虽然是一个奇怪的解决方案,就是将单击的单元格的信息存储在某种隐藏的输入表单中,一旦我将其保存到这些隐藏的输入中,我就会模拟单击也是隐藏表单的提交按钮。这应该有效。

标签: javascript python html flask


【解决方案1】:

对于也有此类用例的任何人,请确保您使用如下方法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 会正确处理所有内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-13
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多