无法从AJAX调用[Flask]接收数据

时间:2017-07-16 17:30:23

标签: python json ajax flask stripe-payments

我正在尝试做什么:从AJAX接收数据到Flask。最后,我想将令牌数据(将来自条纹)发送到烧瓶侧

问题:我无法将任何数据打印到控制台。所以我假设数据没有通过。

我无法从Ajax调用中接收数据。我一直在寻找一段时间,但我还没有找到解决办法。我已经为其他人看到了多种不同的解决方案,但它们都没有为我工作。我正在尝试实施自定义条带付款流程。

我打算最终做的是通过“数据”传递我需要的所有数据(在令牌中)。 JSON格式的参数。以下是代码的不同方面

的index.html

var handler = StripeCheckout.configure({
  key: 'test_key',
  image: 'image_url',
  locale: 'auto',
  token: function(token) {
    $.ajax({
      url: '/charge',
      data: {
        'token': '(data im trying to access/print in app.py)'
      },
      type: 'POST',
      success: function(response) {
        console.log(response);
      },
      error: function(error) {
        console.log("ERROR");
        console.log(error);
      },
      dataType: "json",
      contentType: "application/json"
    });
  }
});

app.py

from flask import Flask, request
import json

@app.route('/charge', methods=['POST'])
def charge():

  # Grab token information
  token = request.form['token']

  # The line below never prints to console
  print(token)

  # This test print statement below never prints to console
  print("This print statement never runs")

没有任何内容打印到控制台。我浪费了太多时间在这上面所以任何线索或指针都会被非常赞赏!

更新

我做了一些由 @Daniel Roseman 建议的更新,但没有任何内容打印到控制台。

2 个答案:

答案 0 :(得分:1)

尝试以下代码

在javascript中:

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

在控制器[充电方法]中:

from flask import Flask
from flask import render_template, request, jsonify

@app.route('/charge', methods=['POST'])
def charge():
    # Grab token information
    token = request.json['token']

    # This is the expected token from json
    print(token)

    # This test print statement below now prints to console
    print("This print statement now runs surely")

    # return JSON
    return jsonify(
        code=0,
        msg="Success"
    )

答案 1 :(得分:0)

您没有发布JSON。

您可以只访问request.form字典中的各个元素,而不是访问request.get_json()。在这种情况下:

token = request.form['token']