jinjia模板和ajax,jquery - AJAX and Jinja2 - Stack Overflow

本文介绍了如何在Flask web框架中处理Ajax GET请求,通过request对象获取JavaScript传递的参数,并在服务器端进行操作。示例展示了如何在客户端使用jQuery发起Ajax请求,以及在服务器端解析并使用这些参数。同时,文章强调了在模板渲染时需将参数显式传递给Jinja2。
摘要由CSDN通过智能技术生成

You need to access the request object on the server side to get the arguments. I'm assuming you're using Flask, but if not, the basic idea should be the same on other web frameworks as well. Let's say you have a simple little index.html, where you use Javascript to make your Ajax query:

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

Note that if you're not using Jinja2 to render the script portion, replace the url_for()-call with the actual URL, so something like /ajax in my example further below:

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

Now, on the server side you would have something like this:

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)

and ajax.html would look something like this for example:

{{ name }}

{{ time }}

So request.args is where you can access the arguments you've passed with GET, but you need to pass them explicitly to Jinja2 with the render_template() call. Jinja2 is just a templating language and it is not aware of your arguments (1) unless you pass them to it.

1) With some exceptions. Flask for example does pass a few arguments to Jinja2 implicitly, like the request object.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值