gpt4 book ai didi

jquery - AJAX 和 Jinja2

转载 作者:行者123 更新时间:2023-12-03 22:50:58 25 4
gpt4 key购买 nike

我想在 Jinja2 模板中使用带参数的 AJAX 调用。但我怎样才能让它成为可能呢?我想做这样的事情。

JavaScript:

$.get("test.html", { name: "John", time: "2pm" } );

神社模板:

<div>
{{name}} {{time}}
</div>

最佳答案

您需要访问服务器端的请求对象来获取参数。我假设您正在使用 Flask,但如果没有,其他 Web 框架的基本思想也应该是相同的。假设您有一个简单的小index.html,您可以在其中使用Javascript 进行Ajax 查询:

$.get("{{ url_for('ajax') }}", {name: "John", time: "2pm"});

请注意,如果您不使用 Jinja2 呈现脚本部分,请将 url_for() 调用替换为实际 URL,例如下面我的示例中的/ajax:

$.get("/ajax", {name: "John", time: "2pm"});

现在,在服务器端您将看到如下内容:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/ajax')
def ajax():

#Access arguments via request.args
name = request.args.get('name')
time = request.args.get('time')

#NOTE: In real code, check that the arguments exist

#Silly logging call to show that arguments are there
app.logger.info(name)
app.logger.info(time)

#Do stuff here to do what you want or modify name/time
...

#Render template and pass the arguments to it
return render_template('ajax.html',
name=name,
time=time)

@app.route('/index')
def index():
return render_template('index.html')

if __name__ == '__main__':
app.run(debug=True)
例如,ajax.html 看起来像这样:

<h2>{{ name }}</h2>
<h2>{{ time }}</h2>

因此 request.args 是您可以访问通过 GET 传递的参数的地方,但您需要使用 render_template() 调用将它们显式传递给 Jinja2。 Jinja2 只是一种模板语言,它不知道您的参数 (1),除非您将它们传递给它。

1) 有一些异常(exception)。例如,Flask 确实隐式向 Jinja2 传递了一些参数,例如请求对象。

关于jquery - AJAX 和 Jinja2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17003968/

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