将变量从Flask路由发送到JavaScript
需要了解如何将变量从Flask路由发送到JavaScript文件以及如何将变量从Flask路由发送到JavaScript文件的帮助 假设我有下面的路线:将变量从Flask路由发送到JavaScript,javascript,python,api,flask,stripe-payments,Javascript,Python,Api,Flask,Stripe Payments,需要了解如何将变量从Flask路由发送到JavaScript文件以及如何将变量从Flask路由发送到JavaScript文件的帮助 假设我有下面的路线: @payment.route('/pay/campaign', methods=['GET', 'POST']) def pay(): user = User.query.get_or_404(campaign.user_id) amount = 1000 return render_template('payment.
@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\u now
这些变量在/pay\u now
路由中用于创建名为clientSecret
的变量,然后我需要将该变量发送回我的JavaScript文件,以便在下面的confirmCardPayment()方法中使用。(如果有一种方法,我可以在/pay
中定义这些变量,并在/pay\u now
中直接访问它们,而无需使用JavaScript,那也行)
总之,我需要:
从/pay
路由将金额
和用户
发送到我的JavaScript文件
然后需要将amount
和user
变量传递到Flask API路由/pay\u now
,该路由创建一个名为clientSecret
最后,获取clientSecret
变量并在JavaScript文件中使用它
如果能在这方面得到一些帮助,那就太棒了!提前谢谢 数据
应该在您的//不确定如何从/pay_now
读取JSON的地方可用?包含console.log(data)
以查看浏览器的调试控制台中有什么要验证的内容可能会很有用。好的,谢谢,我会检查一下。您知道如何从/pay
路径访问JavaScript中的amount
和user
?{{{amount}或{{user}我相信这是您需要的,还有更好的方法。。。但是你可以像“{{amount}}”和“{{user}}”那样做
@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') {
}
}
});
});