Python flask请求返回未定义的值

时间:2019-02-18 16:53:39

标签: python jquery ajax flask

我想将数组传递给Python Flask,但结果为空或b'undefined =&undefined =&undefined ='。这是我的代码 Javascript

var test = [1, 2, 3];
  $.ajax({
        url: '/table',
        data : test,
        type: 'POST',
        success: function(response) {
            console.log(response);
        },
        error: function(error) {
            console.log(error);
        }
    });

和Python代码

app.route('/table', methods = ['POST'])
def table():
    #print(request.values)
    print(request.get_data())
    return 'got this'

2 个答案:

答案 0 :(得分:2)

您需要使用JSON来发送返回值,这些值是javascript中的数组,对象等:

var test = [1, 2, 3];
$.ajax({
    url: '/table',
    data : {'payload':JSON.stringify(test)},
    type: 'get',
    success: function(response) {
        console.log(response);
    },
    error: function(error) {
        console.log(error);
    }
});

然后,在应用程序中:

import json
@app.route('/table')
def table():
  _result = json.loads(flask.request.args.get('payload'))
  return 'got this'

答案 1 :(得分:0)

使用JavaScript对象并作为application/json的内容发送。

var test = {'input_1': 1, 'input_2': 2, 'input_3': 3};
  $.ajax({
        url: '/table',
        data : JSON.stringify(test),
        contentType: 'application/json',
        type: 'POST',
        success: function(response) {
            console.log(response);
        },
        error: function(error) {
            console.log(error);
        }
    });

在flask应用程序中,不需要导入json来加载接收到的数据,因为您已将内容发送为application/json

from flask import jsonify, request

@app.route('/table', methods = ['POST'])
def table():
  _result = request.json  # because you have sent data as content type as application/json
  return jsonify(_result)  # jsonify will response data as `application/json` header.
  #  {'input_1': 1, 'input_2': 2, 'input_3': 3}