有人知道只有在Bootstrap 4表格有效时如何使Stripe付款弹出窗口出现吗?
✓表单无效时,引导代码有效。
问题:我尝试使用'if else'语句使Stripe在表单有效但没有任何反应时出现:(
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form[0].checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
} else {
var handler = StripeCheckout.configure({
key: 'pk_test_zef7efzhke73gefezzzhgu3',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function(token) {
// You can access the token ID with `token.id`.
// Get the token ID to your server-side code for use.
}
});
// Open Checkout with further options:
handler.open({
name: 'Test',
description: '2 widgets',
currency: 'eur',
amount: 2000
});
// Close Checkout on page navigation:
window.addEventListener('popstate', function() {
handler.close();
});
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
答案 0 :(得分:0)
在此引导程序组件的演示代码中,如果验证失败,它们仅阻止提交表单。对于您而言,您想一直防止它发生,否则,一旦验证成功,该页面将重定向到另一个页面(如果未在表单上放置action属性,则重新加载该页面),而不是打开Checkout模式。
最简单的方法是在if语句之前移动以下内容:
event.preventDefault();
event.stopPropagation();
与您的问题无关,但您可能希望将StripeCheckout.configure(...)
部分移到验证逻辑之外,以便在页面加载时仅实例化Checkout一次。
作为参考,这是我用来使其工作的完整代码段,但是您仍然需要在token: function(token) {...}
回调中添加一些代码,以便在完成所有操作后将令牌发送到您的后端:>
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
var handler = StripeCheckout.configure({
key: 'pk_test_g6do5S237ekq10r65BnxO6S0',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function(token) {
// You can access the token ID with `token.id`.
// Get the token ID to your server-side code for use.
}
});
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
event.preventDefault();
event.stopPropagation();
if (form.checkValidity() === false) {
// Custom behavior when Validation fails
} else {
// Open Checkout with further options:
handler.open({
name: 'Test',
description: '2 widgets',
currency: 'eur',
amount: 2000
});
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>