【发布时间】: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