[英]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.