【发布时间】:2016-07-12 12:03:34
【问题描述】:
我正在尝试通过我的网站查询数据库并使用 Jinja 模板动态添加包含结果的列。我正在使用烧瓶和我的意见功能。我正在渲染这样的值
return render_template('query.html',my_list=my_list )
问题是当我加载页面时用户还没有查询数据库,所以 my_list 是空的。用户通过按下 html 页面上的按钮并通过 jquery 发出 ajax 请求来查询数据库。我现在的问题是,即使在页面已经加载之后,是否可以使用 jinja 模板返回 my_list,这意味着我必须再次返回 render_template(在提交按钮之后)才能获取 my_list 的值。
附言我不喜欢使用 json 解析。
这里是一些示例代码。我使用 SubmitterID 列的 IntranetID 和 Platforms 列的平台值查询数据库,以将整个条目连同其余列的值一起返回到数据库。
@app.route('/querydbvalues',methods=['POST', 'GET'])
def querydbvalues():
if request.method == 'POST' or request.method == 'GET':
results = models.mydatabase.query.filter_by(SubmitterID=qIntranetID,Platforms=qPlatform).all()
my_list = [i.user for i in results]
return render_template('query.html',my_list=my_list )
在我的 html 页面上
{% for n in my_list %}
<li>{{n}}</li>
{% endfor %}
在 Javascript 文件中,当您按下按钮时,我会像这样发出 ajax 请求
$("#SearchDatabase").click(function(){
var tmp = document.getElementById("qIntranetID").value;
var tmp2 = document.getElementById("qPlatform").value;
jQuery.ajax({
dataType: "json",
url:"/querydbvalues", //tell the script where to send requests
data:{text:tmp,text2:tmp2},
type:'GET',
contentType: 'application/json',
success: function(results){
//do something
}
});
});
【问题讨论】:
-
你不需要检查请求方法。 Flask 只会将 GET 和 POST 请求路由到该端点。
标签: python ajax flask rendering jinja2