2 回答

TA貢獻1786條經(jīng)驗 獲得超11個贊
問題似乎是因為getElementById調(diào)用只解析recaptcha_response第一種形式的輸入元素,而不是第二種形式。
一個簡單的解決方法是將recaptcha_response每種形式中元素的 id 更改為不同的東西,比如recaptchaResponse1和recaptchaResponse2。那么用于設(shè)置令牌的 Javascript 代碼可能是:
grecaptcha.ready(function () {
grecaptcha.execute('key2', { action: 'contact' }).then(function (token) {
document.getElementById('recaptchaResponse1').value = token;
document.getElementById('recaptchaResponse2').value = token;
});
});
一種更易于維護且適用于任意數(shù)量表單的更好方法是為recaptcha_reponse輸入指定一個類名,并使用該querySelectorAll函數(shù)獲取具有給定類名的所有輸入并更新它們。
<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))
;
});
希望有幫助:)

TA貢獻1779條經(jīng)驗 獲得超6個贊
刪除 id 標(biāo)簽并僅使用名稱標(biāo)簽。
grecaptcha.ready(function () {
grecaptcha.execute({publicKey}, {action: 'forms'}).then(function (token) {
var recaptchaElements = document.getElementsByName('recaptcha');
for (var i = 0; i < recaptchaElements.length; i++) {
recaptchaElements[i].value = token;
}
});
});
添加回答
舉報