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

标签 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 发出请求,且方法具有正确的 url 且操作为 POST,那么一切都会完美运行。虽然,一旦我开始发出 javascript 客户端 POST 请求,它就可以工作,因为我到达了正确的页面,但它呈现不正确+文档就绪上的 javascript 永远不会被执行。

最佳答案

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

关于javascript - 向 Flask render_template 端点发出客户端 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56901179/

相关文章:

javascript - React html 可定制样式

javascript - CSS或JS修改(替换)网页上的每一个字

javascript - 我应该在哪里存储 underscore.js 迭代器?

python - 如何在我的 Python 脚本中运行 PSCP cmd 窗口步骤

python - 替换多索引数据框中的特定值

javascript - 使用纯 JavaScript 交换图像 src

javascript - Javascript:处理用户生成的脚本的最佳方法

javascript - 为什么 "Redirected when going from "/login"to "/"via a navigation guard."出现了?

python - 如何在 BaseHTTPRequestHandler 子类中停止 BaseHTTPServer.serve_forever()?

javascript - 单击 <a href> 时的 Bootstrap flip div 在移动设备上不起作用