Запрос флакона Python возвращает неопределенные значения - PullRequest
0 голосов
/ 18 февраля 2019

Я хочу передать массив в 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 голосов
/ 18 февраля 2019

Используйте объект 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);
        }
    });

. В вашем приложении-колбе нет необходимости импортировать json для загрузки полученных данных, поскольку вы отправили содержимое как * 1006.*.

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}
0 голосов
/ 18 февраля 2019

Вам необходимо использовать 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'
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...