gpt4 book ai didi

python - 如何通过单击 href 函数将值传递给新模板?

转载 作者:太空宇宙 更新时间:2023-11-03 19:48:04 24 4
gpt4 key购买 nike

我想单击 href 并执行 javascript 函数将一些值发布到 python 并使用该数据呈现新模板,这是我的代码。

index.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请求,就像模板被渲染到后台一样,您需要前台请求)

这也是不好的做法,你把脚本放在正文之前,它甚至不应该放在头部,而应该尽可能放在下面

Why is using onClick() in HTML a bad practice?

服务器.py

@app.route('/getvalue', methods=['GET','POST'])
def getvalue():
if request.method=='POST':
data = request.form['jsvalue']
return render_template("index2.html", data=data)

index.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}}

关于python - 如何通过单击 href 函数将值传递给新模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60015836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com