我是 Flask 的新手,正在努力学习。我正在尝试从查询字符串中访问信息。这是我的 html 代码(simplestuff.html,它在模板文件夹中):
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<select onchange="showUser(this.value)">
<option value="1">Get Something</option>
<option value="2">Get Query String</option>
</select>
</form>
</head>
<body>
<p id="demo"></p>
<ol id="new-projects"></ol>
<script>
function showUser(str) {
if (str=="2") {
//Age in the query string.
var age = 30;
//redirecting to a page with the query string in the url.
location.href = "simplestuff.html?age=" + age;
//Using flask to access age in the query string.
$( "#new-projects" ).load( "QueryStringInfo" );
}
}
</script>
</body>
</html>
这是我的 flask 代码 (main.py),它试图在查询字符串中访问年龄:
from flask import Flask, render_template, request
app = Flask(__name__, static_url_path='')
@app.route('/simplestuff')
def render_plot():
return render_template('simplestuff.html')
@app.route('/QueryStringInfo')
def do_something():
#Requesting the age variable in the query string.
age = request.args.get('age')
return age
if __name__ == '__main__':
app.run()
当我运行服务器并转到 127.0.0.1:5000/simplestuff 时,html 页面运行正常。然后,当我选择“获取查询字符串”时,url 会按预期更改,并且会出现查询字符串。但是,当加载 QueryStringInfo 时,返回的是“None”而不是年龄。我在这里做错了什么?
编辑:将 request.form.get('age') 更改为 request.args.get('age')。还更改了打印年龄以返回年龄。 QueryStringInfo 给我一个 500 错误并且没有返回(可能是由于 500 错误)。
最佳答案
您正在尝试的方法不会按照您认为的方式工作。最终的问题是“你想达到什么目的?”
为了在服务器端访问查询字符串,请求中需要包含查询字符串。也就是说,如果您访问:
http://127.0.0.1//QueryStringInfo?age=10
当您访问该路由时,您的处理程序将适本地返回 10。但是,您正在重定向到
http://127.0.0.1/simplestuff?age=10
然后您尝试在没有查询字符串的情况下访问 /QueryStringInfo
,但这种方式根本行不通。
所以你有几个选择。
在
/simplestuff
处理程序中检索age
并将其作为上下文变量传递给模板。@app.route('/simplestuff') def render_plot(): age = request.args.get('age') return render_template('simplestuff.html', age=age)
在你的模板中:
{{ age }}
- 向
"/QueryStringInfo?age="+ age
发出 ajax 请求。但那时我不确定为什么在您已经可以访问查询字符串变量的情况下,您还要发出额外的服务器请求来访问它。
关于jquery - Flask request.form.get 返回 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26079728/