我是新手,我正在努力学习.我试图从查询字符串中访问信息.这是我的HTML代码(simplestuff.html,它位于templates文件夹中):
<!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>
这是我的烧瓶代码(main.py),它试图在查询字符串中访问age:
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”而不是age.我在这做错了什么?
编辑:将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处理程序中检索年龄,并将其作为上下文变量传递给模板.
@app.route('/simplestuff')
def render_plot():
age = request.args.get('age')
return render_template('simplestuff.html', age=age)
在您的模板中:
{{ age }}
>将ajax请求设为“/ QueryStringInfo?age =”age.但是在那时我不确定为什么当你已经有权访问查询字符串变量时,你会发出额外的服务器请求来访问它.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。