【问题标题】:How to access a variable from an ajax/jquery POST rather than a GET如何从 ajax/jquery POST 而不是 GET 访问变量
【发布时间】:2020-04-15 21:23:20
【问题描述】:

这可能是一个简单的问题,但我无法弄清楚。

如果我有这样的更新路线:

@app.route('/update', methods=['GET', 'POST'])
def update():
    x = request.args.get('foo')
    print(x)
    ...

和这样的jquery:

$(document).ready(function(){

  $("#foobar").click(function() {

      $.ajax({
              url: '/update',
              type: "GET",
              data: { foo: 'hello stack exchange!'}
            });
  });

});

我可以访问消息并将其设置为 x,然后打印出hello stack exchange!

但如果我将请求更改为 POST 而不是 GET,我该如何访问它?

@app.route('/update', methods=['GET', 'POST'])
def update():
    x = request['foo'] # THIS DOESN'T WORK
    print(x)
    ...

和这样的jquery:

$(document).ready(function(){

  $("#foobar").click(function() {

      $.ajax({
              url: '/update',
              type: "POST",
              data: { foo: 'hello stack exchange!'}
            });
  });

});

我知道有效负载没有通过 URL,所以我需要将 request.args.get('foo') 更改为其他内容,但如果 request['foo'] 不起作用,那该怎么办?

【问题讨论】:

  • 你尝试使用request.json 吗?

标签: javascript python jquery python-3.x flask


【解决方案1】:

获取请求数据的一些常用方法。

request.form 正文中的键/值对,来自操作后表单或未编码的 XHR 请求。 request.values 组合 args 和 form,如果存在重复键,则首选 args。 request.json 请求 JSON 数据。请求的内容类型必须为 application/json。您可能正在寻找的是request.values.get('foo')。

【讨论】:

    【解决方案2】:

    使用request.get_json() 获取json

    if request.is_json:
       data = request.get_json()
       foo= req_data['foo']    
    

    【讨论】:

      【解决方案3】:

      对于post请求,参数存储在哪里取决于请求的Content-Type头

      • 如果 Content-Type=application/json,则可以通过“request.json”(作为 dict)获取参数

      • 如果 Content-Type='application/x-www-form-urlencoded',则可以通过“request.form”获取参数(作为 dict) ----我猜这是你的场景,

      • 否则,您可能想尝试 request.data(作为字符串)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-29
        • 2011-08-04
        • 2012-03-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多