【问题标题】:AJAX POST data does not show up in PythonAJAX POST 数据不显示在 Python 中
【发布时间】:2023-03-09 14:13:01
【问题描述】:

我使用jQuery 提出这个HTTP POST 请求。

function getData() {

    const data = JSON.stringify({
        "test_id": "1"
    });

    jQuery.post('/getData', data, function (response) {
        alert("success");
        console.log(response)

    }, "json");
}

当我在 Python 中收到请求时,当我尝试打印 request.data 时,字符串为空。

当我附加调试器时,我看到数据在form (request.form) 下。

我怎样才能让它们从request.data 访问?

提前致谢

【问题讨论】:

  • 发送json需要设置content type header。默认为application/x-www-form-urlencoded。要发送编码的表单,请不要使用 JSON.stringify
  • 你在 Python 中使用什么 - Flask、Django 等?也许检查request.json
  • 您正在使用test_id=1 向python POST 请求发送但试图检查变量data
  • @diavolic,是的,当我从邮递员发送相同的请求时,test_id 在request.data
  • @furas,我用的是 Flask

标签: python jquery json ajax flask


【解决方案1】:

您需要将参数发送为{},以便您可以使用contentType

文档:jQuery.post

    jQuery.post({
        url: "/getData",
        data: data,
        success: function (response) {
            alert("success");
            console.log(response);
        },
        dataType: "json",
        contentType: 'application/json'
    });

使用contentType: 'application/json',您应该将其设为request.data,但也应设为request.json,这样会更有用。


最少的工作代码

from flask import Flask, request, render_template_string, jsonify

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template_string('''
<!DOCTYPE html>

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<script>
function getData() {

    const data = JSON.stringify({"test_id": "1"});

    jQuery.post({
        url: "/getData",
        data: data,
        success: function (response) {
            alert("success");
            console.log(response);
        },
        dataType: "json",
        contentType: 'application/json'
    });
}
getData();
</script>
</head>
</html>
''')

@app.route('/getData', methods=['GET', 'POST'])
def get_data():
    print('args :', request.args)
    print('form :', request.form)
    print('data :', request.data)
    print('json :', request.json)
    print('files:', request.files)
    return jsonify(["Hello World"])

if __name__ == '__main__':
    #app.debug = True 
    app.run()  

结果:

args : ImmutableMultiDict([])
form : ImmutableMultiDict([])
data : b'{"test_id":"1"}'
json : {'test_id': '1'}
files: ImmutableMultiDict([])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-25
    • 2014-02-26
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    相关资源
    最近更新 更多