首页 > 解决方案 > 将变量从 Flask 路由发送到 JavaScript

问题描述

需要帮助了解如何将变量从 Flask 路由发送到 JavaScript 文件,反之亦然。

假设我有以下 Flask 路线:

@payment.route('/pay/campaign', methods=['GET', 'POST'])
def pay():
    user = User.query.get_or_404(campaign.user_id)
    amount = 1000
    return render_template('payment.html', amount=amount, user=user)

我想在我的 JavaScript 文件中访问变量amount并将user它们作为 POST 请求发送到另一个 Flask 路由/pay_now

这些变量在/pay_now路由中用于创建一个名为的变量clientSecret,然后我需要将其发送回我的 JavaScript 文件以在下面的confirmCardPayment()方法中使用。(如果有一种方法我可以在其中定义这些变量/pay并直接访问它们/pay_now而无需通过 JavaScript,那也可以)

@payment.route('/pay_now', methods=['GET','POST'])
def create_payment():
    clientSecret = create_secret(amount, user) #assume this creates secret
    return jsonify({"clientSecret": clientSecret})

form.addEventListener('submit', function(ev) {
fetch("/pay_now", {
    method: "POST",
    body: JSON.stringify({
      // not sure how to send amount and user variable to /pay_now
    }),
    headers: {
      "Content-Type": "application/json"
    },

  })
  .then(response => response.json())
  .then(data => {

    // not sure how to read JSON from /pay_now

  });
  
  stripe.confirmCardPayment(clientSecret, {
    payment_method: {
      card: card,
      billing_details: {
        name: 'Jenny Rosen'
      }
    }
  }).then(function(result) {
    if (result.error) {
      console.log(result.error.message);
    } else {
      if (result.paymentIntent.status === 'succeeded') {
      }
    }
  });
});

总之,我需要:

  1. 发送amountuser/pay路由到我的 JavaScript 文件
  2. 然后需要将amountanduser变量传递给 Flask API 路由/pay_now,该路由创建一个名为clientSecret
  3. 最后,获取clientSecret变量并在 JavaScript 文件中使用它

在这方面获得一些帮助会非常棒!提前致谢!

标签: javascriptpythonapiflaskstripe-payments

解决方案


推荐阅读