gpt4 book ai didi

javascript - Recaptcha V3 不适用于具有多种表单的页面

转载 作者:行者123 更新时间:2023-12-01 00:56:43 25 4
gpt4 key购买 nike

我在使用 Google Recaptcha V3 时遇到问题。 Id 确实适用于单个表单,但仅适用于第一个表单(如果页面中有多个表单)。如何使其适用于所有形式?我知道问题出在 id="recaptchaResponse" 但我不知道如何解决这个问题!那里有类似的问题,但找不到解决方案。

Javascript:

<script src="https://www.google.com/recaptcha/api.js?render=key1"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('key2', { action: 'contact' }).then(function (token) {
var recaptchaResponse = document.getElementById('recaptchaResponse');
recaptchaResponse.value = token;
});
});
</script>

表格:

<form class="user" action="" method="post" name="form1" id="form1">
<input type="hidden" name="source" value="form1">

<button type="submit" class="btn btn-success">Submit 1</button>

<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
</form>

<form class="user" action="" method="post" name="form2" id="form2">
<input type="hidden" name="source" value="form2">

<button type="submit" class="btn btn-success">Submit 2</button>

<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
</form>

请帮忙!提前致谢!

最佳答案

问题似乎是因为 getElementById 调用仅解析第一个表单中的 recaptcha_response 输入元素,而不是第二个表单。

一个简单的修复方法是将每个表单中的 recaptcha_response 元素的 ID 更改为不同的内容,例如 recaptchaResponse1recaptchaResponse2。那么设置 token 的 Javascript 代码可以是:

grecaptcha.ready(function () {
grecaptcha.execute('key2', { action: 'contact' }).then(function (token) {
document.getElementById('recaptchaResponse1').value = token;
document.getElementById('recaptchaResponse2').value = token;
});
});

一种更易于维护且适用于任意数量表单的更好方法是为 recaptcha_reponse 输入指定类名,并使用 querySelectorAll 函数获取具有给定类名的所有输入并更新它们。

<form class="user" action="" method="post" name="form1" id="form1">
<input type="hidden" name="source" value="form1">
<button type="submit" class="btn btn-success">Submit 1</button>

<input type="hidden" name="recaptcha_response" class="recaptchaResponse">
</form>

<form class="user" action="" method="post" name="form2" id="form2">
<input type="hidden" name="source" value="form2">
<button type="submit" class="btn btn-success">Submit 2</button>

<input type="hidden" name="recaptcha_response" class="recaptchaResponse">
</form>
grecaptcha
.execute("key", {
action: "contact"
})
.then(function(token) {
document
.querySelectorAll(".recaptchaResponse")
.forEach(elem => (elem.value = token))
;
});

希望有帮助:)

关于javascript - Recaptcha V3 不适用于具有多种表单的页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56515261/

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