javascript - 将变量从 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') {
}
}
});
});
总之,我需要:
- 发送
amount
和user
从/pay
路由到我的 JavaScript 文件 - 然后需要将
amount
anduser
变量传递给 Flask API 路由/pay_now
,该路由创建一个名为clientSecret
- 最后,获取
clientSecret
变量并在 JavaScript 文件中使用它
在这方面获得一些帮助会非常棒!提前致谢!
解决方案
推荐阅读
- typescript - 当我在 TypeScript 中收到“对象可能为空”错误时,我应该怎么做?
- r - 如何从 R 中的特定列中删除“\”符号
- powershell - VS Code 中的 Cmder 集成与 PowerShell 未按预期工作
- python-3.x - 在 Windows 上打开文件名可能包含特殊字符的文件
- c# - 创建 c# SelectList 不指定值
- mysql - 多个连接错误的 SUM 记录
- php - 按名字和姓氏自动完成搜索
- android - 与数据库相关的错误未在 android studio 中创建
- java - 解析页面中的所有元素时,Jsoup 没有获取少数元素的文本
- mysql - 或者在列中设置 Null 值