Flask request.form.get返回None

che*_*gum 4 python ajax jquery flask

我是新手,我正在努力学习.我试图从查询字符串中访问信息.这是我的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>
Run Code Online (Sandbox Code Playgroud)

这是我的烧瓶代码(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()
Run Code Online (Sandbox Code Playgroud)

当我运行服务器并转到127.0.0.1:5000/simplestuff时,html页面运行正常.然后,当我选择"获取查询字符串"时,URL会按预期更改并显示查询字符串.但是,加载QueryStringInfo时,将返回"None"而不是age.我在这做错了什么?

编辑:将request.form.get('age')更改为request.args.get('age).还改变了印刷年龄以恢复年龄.QueryStringInfo给出了500错误并且没有返回(可能是由于500错误).

sbe*_*rry 6

你所尝试的将不会按照你认为的方式工作.最终的问题是"你想要实现什么目标?"

为了能够访问服务器端的查询字符串,查询字符串需要包含在请求中.也就是说,如果您访问以下内容,您的年龄访问将会起作用:

http://127.0.0.1//QueryStringInfo?age=10
Run Code Online (Sandbox Code Playgroud)

当您访问该路由时,您的处理程序将适当地返回10.但是,您将重定向到

http://127.0.0.1/simplestuff?age=10
Run Code Online (Sandbox Code Playgroud)

然后,您尝试在/QueryStringInfo没有查询字符串的情况下访问,并且它根本不起作用.

所以你有几个选择.

  1. 检索age/simplestuff处理程序,并把它传递给模板上下文变量.

    @app.route('/simplestuff')
    def render_plot():
        age = request.args.get('age')  
        return render_template('simplestuff.html', age=age)
    
    Run Code Online (Sandbox Code Playgroud)

在您的模板中:

   {{ age }}
Run Code Online (Sandbox Code Playgroud)
  1. 发出ajax请求"/QueryStringInfo?age=" + age.但是在那时我不确定为什么当你已经有权访问查询字符串变量时,你会发出额外的服务器请求来访问它.