4 回答

TA貢獻1815條經驗 獲得超13個贊
您想要阻止提交表單的默認行為。所以這樣做:
checkoutButton.addEventListener('click', function(event) {
...
if(isFormValid==true) {
event.preventDefault();

TA貢獻1847條經驗 獲得超11個贊
現在,click如果表單在頁面加載時有效,您的代碼僅附加偵聽器。在沒有其他表單行為的情況下,單擊表單中的按鈕會將其提交回其來源的頁面,這就是它看起來像頁面刷新的原因。
您需要將表單檢查移動到按鈕單擊事件處理程序內,如下所示:
<script>
(function() {
var stripe = Stripe('pk_test_xxx');
var checkoutButton = document.getElementById('checkout-button-sku_xxx');
checkoutButton.addEventListener('click', function() {
if($('#tcform')[0].checkValidity()){
// When the customer clicks on the button, redirect
// them to Checkout.
stripe.redirectToCheckout({
items: [{
sku: 'sku_xxx',
quantity: 1
}],
// Do not rely on the redirect to the successUrl for fulfilling
// purchases, customers may not always reach the success_url after
// a successful payment.
// Instead use one of the strategies described in
// https://stripe.com/docs/payments/checkout/fulfillment
successUrl: window.location.protocol + '//www.xxx.com',
cancelUrl: window.location.protocol + '//www.xxx.com',
})
.then(function(result) {
if (result.error) {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer.
var displayError = document.getElementById('error-message');
displayError.textContent = result.error.message;
}
});
}
});
})();
但監聽表單的submit事件可能會更好(https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event):
$('#tcform').on('submit', function() {
stripe.redirectToCheckout({
...
});
});
該submit事件僅在表單驗證后才會發出。

TA貢獻1712條經驗 獲得超3個贊
這也發生在我們身上。
我們已將novalidate
屬性(刪除 HTML5 驗證)添加到表單并僅通過 javascript 進行驗證。
????<form?id="tcform"?novalidate> ????... ????????</form>
- 4 回答
- 0 關注
- 158 瀏覽
添加回答
舉報