我想检测浏览器是否通过AJAX(AngularJS)发出请求,以便我可以返回JSON数组,或者我是否必须呈现模板。我怎么能这样做?
答案 0 :(得分:23)
Flask在is_xhr
对象中附带request
属性。
from flask import request
@app.route('/', methods=['GET', 'POST'])
def home_page():
if request.is_xhr:
context = controllers.get_default_context()
return render_template('home.html', **context)
答案 1 :(得分:1)
无法确定ajax是否发出了请求。
我发现对我有用的只是在xhr请求中包含一个get参数,而在非xhr请求中则省略了该参数。
例如:
example.com/search?q=Boots&api=1
example.com/search?q=Boots
答案 2 :(得分:1)
供将来的读者使用:我的工作如下:
request_xhr_key = request.headers.get('X-Requested-With')
if request_xhr_key and request_xhr_key == 'XMLHttpRequest':
#mystuff
return result
abort(404,description="only xhlhttprequest is allowed")
如果请求标头中不包含“ XMLHttpRequest”值,则会出现404错误。