首页 > 解决方案 > 如何通过单击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() 的数据可以正常工作,但不能渲染到新模板,那么我该如何解决这个问题。

标签: pythonajaxflask

解决方案


伙计,你甚至不需要 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}}

推荐阅读