【问题标题】:Sending JSON to Flask with jQuery gives error [duplicate]使用 jQuery 将 JSON 发送到 Flask 会出错 [重复]
【发布时间】:2016-11-24 15:14:26
【问题描述】:

我想使用 jQuery 将 JSON 数据发送到 Flask 路由。但是,request.get_json() 给出了错误。为什么这不起作用?

my_array = {"student_data":{"actual_data":12,"sheet_data":23,"age":"20"},"teacher_data":{"actual_data":193,"sheet_data":203,"age":"40"},"school_data":{"actual_data":593,"sheet_data":29,"age":"49"}};
$.ajax({
    url: '/submit_method',
    data: my_array,
    contentType: 'application/json; charset=utf-8',
    type : 'GET',                         
    async: 'false',
    success: function (serverResponse) {          
    }
});
@app.route('/submit_method', methods=['GET'])
def submit_method():
    k = request.get_json()
    return ''

【问题讨论】:

    标签: python json flask


    【解决方案1】:

    您必须使用 POST 方法而不是 GET。

        @app.route('/submit_method', methods=['POST'])
        def submit_method():
            k = request.data     # gets request body in form of dictionary
            return json.dumps(k) # converts dictionary to json
    
    
       $.ajax({
         url: '/submit_method',  data:   JSON.stringify(my_array),  
         contentType:"application/json; charset=utf-8", 
         type : 'POST', async: "false",  success  : function (serverResponse) {}});
    

    【讨论】:

      【解决方案2】:

      问题是必须首先使用 JSON.stringify 将 JavaScript 转换为 JSON 字符串。否则 Flask 将不会认为它是 application/json 内容类型并以 400 拒绝请求。

      $.ajax({
          url: '/submit_method',
          data: JSON.stringify(my_array),
          contentType: 'application/json; charset=utf-8',
          type : 'GET',                         
          async: 'false',
          success: function (serverResponse) {          
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2018-09-13
        • 2019-05-10
        • 1970-01-01
        • 2020-11-21
        • 1970-01-01
        • 2011-06-27
        • 2018-05-20
        • 2018-01-06
        • 2016-09-13
        相关资源
        最近更新 更多