[英]Uncaught ReferenceError: Stripe is not defined - STRIPE ERROR
我正在尝试将 Stripe 元素实现到我的 rails 应用程序中,但我似乎无法正确包含 stripe.js。 这是我的应用程序。html
<%= tag :meta, name: "stripe-key", content: Figaro.env.stripe_publishable_key %>
<script type="text/javascript" src="https://js.stripe.com/v3/"</script>
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
var stripe = Stripe($("meta[name='stripe-key']").attr("content"))
var elements = stripe.elements();
var card = elements.create('card', {
style: {
base: {
iconColor: '#999',
color: '#505652',
lineHeight: '40px',
fontWeight: 300,
fontFamily: 'Helvetica Neue',
'::placeholder': {
color: '#CFD7E0',
},
},
}
});
// Add an instance of the card UI component into the `card-element` <div>
card.mount('#card-element');
<form action="/charge" method="post" id="payment-form">
<div class="form-row">
<label for="card-element">
Credit or debit card
</label>
<div id="card-element">
</div>
<div id="card-errors"></div>
</div>
<button>Submit Payment</button>
</form>
每次加载页面时,我都会在控制台中收到此错误Uncaught ReferenceError: Stripe is not defined - STRIPE ERROR
。 我认为这与我加载 stripe.js 的方式有关,但我不确定?
我怀疑正在发生的事情是 Stripe.js 在你自己的 javascript 之后加载。 尝试将 Stripe.js 移到标题中您自己的 javascript 上方。
可能会迟到,但如果其他人有同样的问题,只需在您的
<HEAD></HEAD>
<script src="https://js.stripe.com/v2/"></script>
知道他们建议尽快迁移到 v3。
Stripe.js 现在在所有其他脚本之后加载,这意味着它不再立即可用。 我已将脚本从 body 标签移动到 head 标签。
<head>
<script src="https://js.stripe.com/v3/"></script>
</head>
你可能会使用这样的东西
<%= javascript_include_tag 'https://js.stripe.com/v3/', 'data-turbolinks-track': 'reload' %>
让我失望的是他们的文档有教程,他们跳过了 Stripe 库的初始化。 因此,如果您从这些教程之一开始并尝试他们的示例代码,它将无法正常工作。
相反,您需要在脚本中的某处添加这一行:
var stripe = Stripe("your_stripe_publishable_key");
Just init stripe just if function Stripe() is a function, and go retry with an interval every 500ms till the function is defined.
之后,清除间隔。
因此,您可以推迟条带脚本并提高页面加载速度
/// init stripe var
var stripe; var stripeElements;
var setStripe = setInterval(function(){
if (typeof Stripe === "function"){
stripe = Stripe('YOUR PUBLIC KEY');
stripeElements = stripe.elements();
clearInterval(setStripe);
}
},500);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.