【问题标题】:Sending a dictionary from JS to Flask via AJAX [duplicate]通过 AJAX 将字典从 JS 发送到 Flask [重复]
【发布时间】:2019-09-25 17:29:25
【问题描述】:

我正在尝试通过 AJAX 从客户端 JavaScript 以字典格式将数据发送到服务器后端。它正在工作,但是在 Python 端收到的数据不是我所期望的。

>>> b'new+class=some_valaue&document+id=1234567'

我期待的是:

{'new class': 'some_value', 'document id': 1234567}

我的 javascript

    $.ajax({
            url: '/reclassify',
            data: {'new class': 'some_value',
            'document id': 1234567,},
            type: 'POST',
            success: function(response){
                console.log(response);
            },
            error: function(error){
                console.log(error);
            }
        });

我的 Python/Flask

@app.route('/reclassify', methods=['POST'])
def reclassify():
    data = request.get_data()
    print(data)
    return 'success'

我还没有任何 if POST 语句,因为我仍在尝试弄清楚如何以正确的格式发送数据。

【问题讨论】:

  • 在 ajax 请求中调用 JSON.stringify(data) 有帮助吗?您也可以尝试将contentType: 'application/json' 添加到请求对象中,例如this post。然后在后端使用this post。
  • 我之前试过,结果很奇怪,再试一次,它似乎工作:D

标签: javascript python flask


【解决方案1】:

Python

@app.route('/reclassify', methods=['POST'])
def reclassify():
    if request.method == 'POST':
        data = request.get_json()
        print(data)

    return '', 200

JS

    function updateClassifier(e, id) {
        let newClassData = {
        'new class': 'some_value',
            'document id': 1234567,
        }

    $.ajax({
            url: '/reclassify',
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify({newClassData}),
            dataType: "json",
            type: 'POST',
            success: function(response){
                console.log(response);
            },
            error: function(error){
                console.log(error);
            }
        });
}

python 输出

{'newClassData': {'new class': 'some_value', 'document id': '1234567'}}

【讨论】:

    猜你喜欢
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 2013-11-04
    • 2014-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多