gpt4 book ai didi

javascript - 如何防止js函数在页面加载时执行

转载 作者:行者123 更新时间:2023-11-30 05:46:33 26 4
gpt4 key购买 nike

我尝试在单击表单 send_button 后使用 sendPostAjax() 函数发送确认邮件,然后将表单提交给支付提供商。但是在点击之前,我在页面加载时执行了 sendPostAjax() 函数。

我尝试将 sendPostAjax() 函数放在点击捕获中,但由于 sendPostAjax() 函数未定义,因此无法分配 promise。

我应该如何解决这个问题有什么建议吗?

HTML 格式

<form id="payment" method="post" action="https://my-payment-provider.com">
<input type="hidden" name="charset" value="utf-8">
// --- additional data here
<button type="submit" name="submit" id="send_button">PAY</button>
</form>

JavaScript 代码

<script type = "text/javascript">
// Get click and call sendPostAjax function
document.getElementById('send_button').addEventListener('click', function () {
sendPostAjax();
return false;
});

function sendPostAjax() {
return $.ajax({
url: 'confirm.php',
type: 'POST',
data: {
cid: '9999999'
}
});
}

// function that expects a promise as an argument:
function sendForm(x) {
x.success(function () {
$('#payment').submit;
});
}

// get a promise from sendPostAjax:
var promise = sendPostAjax();

// give a promise to other function:
sendForm(promise);
</script>

最佳答案

您可以使用 jQuery 按钮单击处理程序来执行此操作,将您的代码替换为以下代码并尝试:

更新代码(ajax 成功 后提交表单):

$('#send_button').click(function() {
var form = $('#payment');
if (form.attr('confirm') === undefined) {
$.ajax({
url: 'confirm.php',
type: 'POST',
data: {
cid: '9999999'
},
success: function(data) {
form.attr('confirm', '1');
$('#send_button').click();
}
});
return false;
}

return true;
});

关于javascript - 如何防止js函数在页面加载时执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17636867/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com