请求客户机POSTFlask渲染\u模板endpoin

2024-04-24 22:10:44 发布

您现在位置:Python中文网/ 问答频道 /正文

在这里和网上找了很久,我找不到我需要的东西。这是一个关于我的问题的最简单可验证的例子。在

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

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

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

以下是文件: index.html

^{pr2}$

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 on document ready永远不会执行。在


Tags: theindexonrequesthtmlpagescripttemplate
1条回答
网友
1楼 · 发布于 2024-04-24 22:10:44

对于任何拥有这样一个用例的人,请确保使用如下方法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将正确处理所有内容。在

相关问题 更多 >