python - 如何通过单击href函数将值传递给新模板?
问题描述
我想单击 href 并执行 javascript 函数以向 python 发布一些值并使用该数据呈现新模板,这是我的代码。
索引.html
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<body>
<a href="#" onclick="myFunction();">Click</a>
<script>
var jsvariable = 'hello world'
function myFunction(){
$.ajax({
url: "/getvalue",
type: "post", //send it through get method
data:{'jsvalue': jsvariable},
})
}
</script>
</body>
</html>
服务器.py
from flask import Flask, render_template, request, url_for
app = Flask(__name__)
@app.route('/', methods=['GET','POST'])
def index():
return render_template('index.html')
@app.route('/getvalue', methods=['GET','POST'])
def getvalue():
data = request.form['jsvalue']
print(data)
return render_template('index2.html', data=data)
if __name__ == "__main__":
app.run(debug=True)
现在从 ajax 函数传递到 python 中的 getvalue() 的数据可以正常工作,但不能渲染到新模板,那么我该如何解决这个问题。
解决方案
伙计,你甚至不需要 ajax (我什至认为这对你来说是个问题,如果我错了,请纠正我,但 ajax 会发出后台 POST 请求,就像模板被渲染到后台一样,你需要一个前台请求)
也是不好的做法,你把你的脚本放在身体之前,它甚至不应该放在头上,而是尽可能地往下走
为什么在 HTML 中使用 onClick() 是一种不好的做法?
服务器.py
@app.route('/getvalue', methods=['GET','POST'])
def getvalue():
if request.method=='POST':
data = request.form['jsvalue']
return render_template("index2.html", data=data)
索引.html
<form action = "/getvalue" method = "POST">
<input type = "hidden" name = "jsvalue"/>
<input type = "submit" value = "submit"/>
</form>
<script>
var jsvariable = 'hello world';
var el=document.getElementsByName("jsvalue");
el[0].value=jsvariable;
</script>
index2.html
{{data}}
推荐阅读
- r - lpSolveAPI 中的目标值和约束值是内生的
- c# - How to change storage class of single object in GCS bucket?
- objective-c - CAReplicatorLayer的速度等于0时,复制效果消失
- apache-spark-sql - 从火花中的数据框中选择值
- php - 无法在仪表板中显示 Laravel Voyager 小部件
- unity3d - 实例化 2mb 预制件需要很长时间并且滞后于游戏
- javascript - ajax response not populating INSIDE html tag
Not exactly sure where I went wrong here but I want the content of the response to populate inside the html tags. I'm thinking first I append the table tag, header. Then let the function popul
- machine-learning - 评估没有标签的测试数据集!- 可以评估吗?
- python - AWS Lambda 函数中的音频文件到文本转换
- opcode - github 上的 riscv-opcodes 与 risc-v 规范中的 opcodes 不同