jQuery   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了jquery – AJAX和Jinja2大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

我想在Jinja2模板中使用带参数的AJAX调用.但是我如何才能实现呢?我想做这样的事情.

JavaScript的:

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

jinja模板:

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

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

请注意,如果您没有使用Jinja2来呈现脚本部分,请将url_for() – 调用替换为实际的URL,所以我的示例中的/ ajax更像下面的内容

$.get("/ajax",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看起来像这样的例子:

所以request.args是你可以访问你用GET传递的参数的地方,但你需要使用render_template()调用将它们显式传递给Jinja2. Jinja2只是一种模板化的语言,它不知道你的论点(1),除非你把它们传递给它.

1)除了一些例外.例如,Flask会像请求对象一样隐式地向Jinja2传递一些参数.

大佬总结

以上是大佬教程为你收集整理的jquery – AJAX和Jinja2全部内容,希望文章能够帮你解决jquery – AJAX和Jinja2所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。