【问题标题】:Why my flask app can't recive json from javascript? [duplicate]为什么我的烧瓶应用程序无法从 javascript 接收 json? [复制]
【发布时间】:2017-09-13 07:03:54
【问题描述】:

我尝试将 json 数据从 JavaScript 发送到 flaskapp。但是从javascript传过来的json数据没有被flask接受,请求为null,哪里出错了?

这是我的烧瓶代码。

@main.route('/getjson', methods = ['GET', 'POST'])
def getjson():
    a = request.json
    return jsonify(user = a)

这是我的 javascript 代码。

$(function(){
    $("#test").click(function(){
        $.ajax({
            url: "{{ url_for('main.getjson') }}",
            type: "POST",
            data: JSON.stringify({
                "n1": "test1",
                "n2": "test2",
                "n3": "test3"
            }),
            dataType: "json",
            success: function(data){
                var a = data.user
                var texthtml = "<p>" + a + "</p>"
                $("#result").html(texthtml)
            }
        });
    });
});

页面返回的数据始终为空。 Request.arg.get 也不起作用。

【问题讨论】:

    标签: javascript python json flask


    【解决方案1】:

    Flask 的request.json 需要application/json 内容类型,但$.ajax 默认设置application/x-www-form-urlencoded。发出请求时设置内容类型。

    $.ajax({
            url: "{{ url_for('main.getjson') }}",
            type: "POST",
            data: JSON.stringify({
                "n1": "test1",
                "n2": "test2",
                "n3": "test3"
            }),
            contentType: "application/json",
            dataType: "json",
            success: function(data){
                var a = data.user
                var texthtml = "<p>" + a + "</p>"
                $("#result").html(texthtml)
            }
        });
    

    或者,发送对象本身,不带JSON.stringify()

    $.ajax({
            url: "{{ url_for('main.getjson') }}",
            type: "POST",
            data: {
                n1: "test1",
                n2: "test2",
                n3: "test3"
            },
            dataType: "json",
            success: function(data){
                var a = data.user
                var texthtml = "<p>" + a + "</p>"
                $("#result").html(texthtml)
            }
        });
    

    这将以表单编码的形式发送数据,因此您可以在 Flask 中使用request.form 来读取它。

    dataType 是您希望从服务器接收的数据类型,而contentType 是您发送到服务器的数据类型。

    见:

    【讨论】:

      猜你喜欢
      • 2020-05-05
      • 2022-01-25
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-23
      相关资源
      最近更新 更多