我是新手,我正在努力学习。我试图从查询字符串中访问信息。这是我的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>
以下是试图在查询字符串中访问年龄的烧瓶代码(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页面运行正常。然后当我选择&#34;获取查询字符串&#34; url按预期更改并显示查询字符串。但是,当QueryStringInfo被加载时,&#34;无&#34;返回而不是年龄。我在这里做错了什么?
修改:将request.form.get(&#39; age&#39;)更改为request.args.get(&#39; age)。还改变了印刷年龄以恢复年龄。 QueryStringInfo给出了500错误并且没有返回(可能是由于500错误)。
答案 0 :(得分:5)
你所尝试的将不会按照你认为应该的方式运作。最终的问题是“你想要实现什么?”
为了能够访问服务器端的查询字符串,查询字符串需要包含在请求中。也就是说,如果您访问了以下内容,您的年龄访问将会起作用:
http://127.0.0.1//QueryStringInfo?age=10
当您访问该路线时,您的处理程序将适当地返回10.但是,您将重定向到
http://127.0.0.1/simplestuff?age=10
然后,您尝试在没有查询字符串的情况下访问/QueryStringInfo
,并且它不会以这种方式工作。
所以你有几个选择。
在age
处理程序中检索/simplestuff
,并将其作为上下文变量传递给模板。
@app.route('/simplestuff')
def render_plot():
age = request.args.get('age')
return render_template('simplestuff.html', age=age)
在你的模板中:
{{ age }}
"/QueryStringInfo?age=" + age
发出ajax请求。但是在那时我不确定为什么当你已经有权访问查询字符串变量时,你会发出额外的服务器请求来访问它。 答案 1 :(得分:0)
您正在打印age
而非返回
@app.route('/QueryStringInfo')
def do_something():
#Requesting the age variable in the query string.
length = request.form.get('age')
print age # should be return age
Python默认为没有返回值的函数返回None
修改强>
此外,该函数中未定义age
。获得'age'
查询字符串后,您将其存储在名为length
的变量中。 age
是全球性的吗?
答案 2 :(得分:0)
不要忘记添加GET和POST方法。
@app.route('/QueryStringInfo',methods=['GET','POST'])
def do_something():
#Requesting the age variable in the query string.
age = request.args.get('age')
return age